From 9f682542e3fcafe8b70d9c0a99e7af8760a1b0bb Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 18:54:20 +0500 Subject: [PATCH 01/71] BulkOperation tests improvements to work correctly --- .../Other.cs | 412 +++++---- .../ReferenceFields.cs | 857 +++++++++--------- 2 files changed, 691 insertions(+), 578 deletions(-) diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs index 00791c25e7..98be7bf083 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012-2020 Xtensive LLC. +// Copyright (C) 2012-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexander Ovchinnikov @@ -18,228 +18,266 @@ internal class Other : AutoBuildTest [Test] public void CompositeKeyUpdate() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - DateTime date1 = DateTime.Now; - DateTime date2 = DateTime.Now.AddDays(1); - Guid id1 = Guid.NewGuid(); - Guid id2 = Guid.NewGuid(); - var foo1 = new Bar2(session, date1, id1) {Name = "test"}; - var foo2 = new Bar2(session, date2, id1); - var foo3 = new Bar2(session, date2, id2) {Name = "test"}; - int updated = session.Query.All().Where(a => a.Name=="test").Set(a => a.Name, "abccba").Update(); - Assert.That(updated, Is.EqualTo(2)); - Assert.That(foo1.Name, Is.EqualTo("abccba")); - Assert.That(foo3.Name, Is.EqualTo("abccba")); - Assert.That(foo2.Name, Is.Null); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var date1 = FixDateTimeForPK(DateTime.Now); + var date2 = FixDateTimeForPK(DateTime.Now.AddDays(1)); + var id1 = Guid.NewGuid(); + var id2 = Guid.NewGuid(); + session.SaveChanges(); + var foo1 = new Bar2(session, date1, id1) { Name = "test" }; + var foo2 = new Bar2(session, date2, id1); + var foo3 = new Bar2(session, date2, id2) { Name = "test" }; + var updated = session.Query.All().Where(a => a.Name == "test").Set(a => a.Name, "abccba").Update(); + Assert.That(updated, Is.EqualTo(2)); + Assert.That(foo1.Name, Is.EqualTo("abccba")); + Assert.That(foo3.Name, Is.EqualTo("abccba")); + Assert.That(foo2.Name, Is.Null); + trx.Complete(); } } [Test] public void SimpleDelete() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar1 = new Bar(session) {Name = "test", Count = 3}; - var bar2 = new Bar(session); - var bar3 = new Bar(session); - bar3.Foo.Add(new Foo(session) {Name = "Foo"}); - string s = "test"; - - int deleted = session.Query.All().Where(a => a.Name==s).Delete(); - Assert.That(bar1.IsRemoved, Is.True); - Assert.That(bar2.IsRemoved, Is.False); - Assert.That(bar3.IsRemoved, Is.False); - Assert.That(deleted, Is.EqualTo(1)); - - session.Query.All().Where(a => a.Foo.Any(b => b.Name=="Foo")).Update(a => new Bar(null) {Name = ""}); - deleted = session.Query.All().Where(a => a.Foo.Count(b => b.Name=="Foo")==0).Delete(); - Assert.That(bar2.IsRemoved, Is.True); - Assert.That(bar3.IsRemoved, Is.False); - Assert.That(deleted, Is.EqualTo(1)); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar1 = new Bar(session) { Name = "test", Count = 3 }; + var bar2 = new Bar(session); + var bar3 = new Bar(session); + _ = bar3.Foo.Add(new Foo(session) { Name = "Foo" }); + string s = "test"; + + int deleted = session.Query.All().Where(a => a.Name == s).Delete(); + Assert.That(bar1.IsRemoved, Is.True); + Assert.That(bar2.IsRemoved, Is.False); + Assert.That(bar3.IsRemoved, Is.False); + Assert.That(deleted, Is.EqualTo(1)); + + _ = session.Query.All().Where(a => a.Foo.Any(b => b.Name == "Foo")).Update(a => new Bar(null) { Name = "" }); + deleted = session.Query.All().Where(a => a.Foo.Count(b => b.Name == "Foo") == 0).Delete(); + Assert.That(bar2.IsRemoved, Is.True); + Assert.That(bar3.IsRemoved, Is.False); + Assert.That(deleted, Is.EqualTo(1)); + trx.Complete(); } } [Test] public void SimpleInsert() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - string s1 = "abccba"; - int i = 5; - Key key = - session.Query.Insert(() => new Bar(session) {Name = "test1" + s1, Count = i * 2 + 1, Description = null}); - Assert.That(key, Is.EqualTo(Key.Create(session.Domain, 1))); - var bar = session.Query.Single(key); - Assert.That(bar.Name, Is.EqualTo("test1abccba")); - Assert.That(bar.Count, Is.EqualTo(11)); - Assert.That(bar.Description, Is.Null); - - key = - session.Query.Insert( - () => new Bar(session) {Id = 100, Name = "test" + s1, Count = i * 2 + 1, Description = null}); - Assert.That(key, Is.EqualTo(Key.Create(session.Domain, 100))); - bar = session.Query.Single(key); - Assert.That(bar.Name, Is.EqualTo("testabccba")); - Assert.That(bar.Count, Is.EqualTo(11)); - Assert.That(bar.Description, Is.Null); - - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var s1 = "abccba"; + var i = 5; + var key = + session.Query.Insert(() => new Bar(session) { Name = "test1" + s1, Count = i * 2 + 1, Description = null }); + Assert.That(key, Is.EqualTo(Key.Create(session.Domain, 1))); + var bar = session.Query.Single(key); + Assert.That(bar.Name, Is.EqualTo("test1abccba")); + Assert.That(bar.Count, Is.EqualTo(11)); + Assert.That(bar.Description, Is.Null); + + key = + session.Query.Insert( + () => new Bar(session) { Id = 100, Name = "test" + s1, Count = i * 2 + 1, Description = null }); + Assert.That(key, Is.EqualTo(Key.Create(session.Domain, 100))); + bar = session.Query.Single(key); + Assert.That(bar.Name, Is.EqualTo("testabccba")); + Assert.That(bar.Count, Is.EqualTo(11)); + Assert.That(bar.Description, Is.Null); + + trx.Complete(); } } [Test] public void SimpleUpdate() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar1 = new Bar(session) {Name = "test", Count = 3}; - var bar2 = new Bar(session); - string s = "test"; - string s1 = "abccba"; - int updated = - session.Query.All().Where(a => a.Name.Contains(s)).Update( - a => new Bar(session) {Name = a.Name + s1, Count = a.Count * 2, Description = null}); - Assert.That(bar1.Name, Is.EqualTo("testabccba")); - Assert.That(bar1.Description, Is.Null); - Assert.That(bar1.Count, Is.EqualTo(6)); - Assert.That(updated, Is.EqualTo(1)); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar1 = new Bar(session) { Name = "test", Count = 3 }; + var bar2 = new Bar(session); + var s = "test"; + var s1 = "abccba"; + var updated = + session.Query.All().Where(a => a.Name.Contains(s)).Update( + a => new Bar(session) { Name = a.Name + s1, Count = a.Count * 2, Description = null }); + Assert.That(bar1.Name, Is.EqualTo("testabccba")); + Assert.That(bar1.Description, Is.Null); + Assert.That(bar1.Count, Is.EqualTo(6)); + Assert.That(updated, Is.EqualTo(1)); + trx.Complete(); } } [Test] public void SubqueryInsert() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - new Foo(session) {Name = "test"}; - new Bar(session) {Name = "test1"}; - session.SaveChanges(); - Key key = null; - session.AssertCommandCount( - Is.EqualTo(1), - () => { key = session.Query.Insert(() => new Bar(session) {Count = session.Query.All().Max(b => b.Count)}); }); - var bar = session.Query.Single(key); - Assert.That(bar.Count, Is.EqualTo(0)); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + _ = new Foo(session) { Name = "test" }; + _ = new Bar(session) { Name = "test1" }; + session.SaveChanges(); + Key key = null; + session.AssertCommandCount( + Is.EqualTo(1), + () => { key = session.Query.Insert(() => new Bar(session) { Count = session.Query.All().Max(b => b.Count) }); }); + var bar = session.Query.Single(key); + Assert.That(bar.Count, Is.EqualTo(0)); + trx.Complete(); } } [Test] - public void SubqueryUpdate() + public void SubqueryUpdate1() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar(session); - var bar2 = new Bar(session) {Count = 1}; - new Foo(session) {Bar = bar, Name = "test"}; - new Foo(session) {Bar = bar, Name = "test1"}; - session.Query.All().Where(a => a.Count==a.Foo.Count - 2).Set(a => a.Count, a => a.Foo.Count).Update(); - Assert.That(bar.Count, Is.EqualTo(2)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => session.Query.All().Where(a => a.Count==session.Query.All().Max(b => b.Count) + 1).Set(a => a.Count, a => session.Query.All().Min(b => b.Count)).Update()); - Assert.That(bar.Count, Is.EqualTo(2)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => session.Query.All().Where(a => a.Count==session.Query.All().Max(b => b.Count) + 1).Set(a => a.Count, a => session.Query.All().Count()).Update()); - - trx.Complete(); - } + CheckSetFromSelectSupported(); + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar(session); + var bar2 = new Bar(session) { Count = 1 }; + _ = new Foo(session) { Bar = bar, Name = "test" }; + _ = new Foo(session) { Bar = bar, Name = "test1" }; + _ = session.Query.All().Where(a => a.Count == a.Foo.Count - 2).Set(a => a.Count, a => a.Foo.Count).Update(); + Assert.That(bar.Count, Is.EqualTo(2)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => session.Query.All().Where(a => a.Count == session.Query.All().Max(b => b.Count) + 1).Set(a => a.Count, a => session.Query.All().Min(b => b.Count)).Update()); + Assert.That(bar.Count, Is.EqualTo(2)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => session.Query.All().Where(a => a.Count == session.Query.All().Max(b => b.Count) + 1).Set(a => a.Count, a => session.Query.All().Count()).Update()); + + trx.Complete(); } + } [Test] - public void UpdateViaSet() + public void SubqueryUpdate2() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar1 = new Bar(session) {Name = "test", Count = 3}; - var bar2 = new Bar(session); - string s = "test"; - string s1 = "abccba"; - int updated = - session.Query.All().Where(a => a.Name.Contains(s)).Set(a => a.Name, s1).Set( - a => a.Count, a => a.Count * 2).Set(a => a.Description, a => a.Name + s1).Update(); - Assert.That(bar1.Name, Is.EqualTo("abccba")); - Assert.That(bar1.Description, Is.EqualTo("testabccba")); - Assert.That(bar1.Count, Is.EqualTo(6)); - Assert.That(updated, Is.EqualTo(1)); - trx.Complete(); - } + CheckSetFromSelectUnsupported(); + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar(session); + var bar2 = new Bar(session) { Count = 1 }; + _ = new Foo(session) { Bar = bar, Name = "test" }; + _ = new Foo(session) { Bar = bar, Name = "test1" }; + _ = Assert.Throws( + () => session.Query.All().Where(a => a.Count == session.Query.All().Max(b => b.Count) + 1) + .Set(a => a.Count, a => session.Query.All().Min(b => b.Count)) + .Update()); + + trx.Complete(); + } + } + + [Test] + public void UpdateViaSet1() + { + CheckGroupSetApplication(); + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar1 = new Bar(session) { Name = "test", Count = 3 }; + var bar2 = new Bar(session); + var s = "test"; + var s1 = "abccba"; + var updated = session.Query.All().Where(a => a.Name.Contains(s)) + .Set(a => a.Name, s1) + .Set(a => a.Count, a => a.Count * 2) + .Set(a => a.Description, a => a.Name + s1) + .Update(); + Assert.That(bar1.Name, Is.EqualTo("abccba")); + Assert.That(bar1.Description, Is.EqualTo("testabccba")); + Assert.That(bar1.Count, Is.EqualTo(6)); + Assert.That(updated, Is.EqualTo(1)); + trx.Complete(); + } + } + + [Test] + public void UpdateViaSet2() + { + CheckOneByOneSetApplication(); + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar1 = new Bar(session) { Name = "test", Count = 3 }; + var bar2 = new Bar(session); + var s = "test"; + var s1 = "abccba"; + var updated = + session.Query.All().Where(a => a.Name.Contains(s)).Set(a => a.Name, s1).Set( + a => a.Count, a => a.Count * 2).Set(a => a.Description, a => a.Name + s1).Update(); + Assert.That(bar1.Name, Is.EqualTo("abccba")); + Assert.That(bar1.Description, Is.EqualTo("abccbaabccba")); + Assert.That(bar1.Count, Is.EqualTo(6)); + Assert.That(updated, Is.EqualTo(1)); + trx.Complete(); } } [Test] public void UpdateWithReferenceToUpdatingEntity() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var foo1 = new Foo(session) {Name = "Test"}; - var foo2 = new Foo(session); - var foo3 = new Foo(session) {Name = "Test1"}; - var bar1 = new Bar(session) {Name = "Test"}; - var bar2 = new Bar(session); - Assert.Throws(()=>session.Query.All().Set(a => a.Bar, a => session.Query.All().First(b => b.Name==a.Name)).Update()); - Assert.That(foo1.Bar, Is.Null); - Assert.That(foo2.Bar, Is.Null); - Assert.That(foo3.Bar, Is.Null); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var foo1 = new Foo(session) {Name = "Test"}; + var foo2 = new Foo(session); + var foo3 = new Foo(session) {Name = "Test1"}; + var bar1 = new Bar(session) {Name = "Test"}; + var bar2 = new Bar(session); + _ = Assert.Throws(()=>session.Query.All().Set(a => a.Bar, a => session.Query.All().First(b => b.Name==a.Name)).Update()); + Assert.That(foo1.Bar, Is.Null); + Assert.That(foo2.Bar, Is.Null); + Assert.That(foo3.Bar, Is.Null); + trx.Complete(); } } [Test] public void In() { - using (Session session = Domain.OpenSession()) - using (TransactionScope trx = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { var bar1 = new Bar(session, 1); var bar3 = new Bar(session, 3); var bar5 = new Bar(session, 5); var bar6 = new Bar(session, 6); var list = new List() {1, 2, 3, 4, 5}; - session.Query.All() - .Where(a => a.Id.In(IncludeAlgorithm.Auto, list)) - .Set(a => a.Count, 2) - .Update(); + _ = session.Query.All() + .Where(a => a.Id.In(IncludeAlgorithm.Auto, list)) + .Set(a => a.Count, 2) + .Update(); Assert.That(bar1.Count, Is.EqualTo(2)); Assert.That(bar3.Count, Is.EqualTo(2)); Assert.That(bar5.Count, Is.EqualTo(2)); Assert.That(bar6.Count, Is.EqualTo(0)); - session.Query.All() - .Where(a => a.Id.In(IncludeAlgorithm.ComplexCondition, list)) - .Set(a => a.Count, 3) - .Update(); + _ = session.Query.All() + .Where(a => a.Id.In(IncludeAlgorithm.ComplexCondition, list)) + .Set(a => a.Count, 3) + .Update(); Assert.That(bar1.Count, Is.EqualTo(3)); Assert.That(bar3.Count, Is.EqualTo(3)); Assert.That(bar5.Count, Is.EqualTo(3)); Assert.That(bar6.Count, Is.EqualTo(0)); - session.Query.All() - .Where(a => a.Id.In(list)) - .Set(a => a.Count, 4) - .Update(); + _ = session.Query.All() + .Where(a => a.Id.In(list)) + .Set(a => a.Count, 4) + .Update(); Assert.That(bar1.Count, Is.EqualTo(4)); Assert.That(bar3.Count, Is.EqualTo(4)); Assert.That(bar5.Count, Is.EqualTo(4)); Assert.That(bar6.Count, Is.EqualTo(0)); - session.Query.All() - .Where(a => a.Id.In(1, 2, 3, 4, 5)) - .Set(a => a.Count, 5) - .Update(); + _ = session.Query.All() + .Where(a => a.Id.In(1, 2, 3, 4, 5)) + .Set(a => a.Count, 5) + .Update(); Assert.That(bar1.Count, Is.EqualTo(5)); Assert.That(bar3.Count, Is.EqualTo(5)); Assert.That(bar5.Count, Is.EqualTo(5)); @@ -252,8 +290,8 @@ public void In() [Test] public void InWithCombinationWithFieldUsageUpdate() { - using (Session session = Domain.OpenSession()) - using (TransactionScope trx = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { var idsToUpdate = new[] { 99, 100, 102 }; var prefix = "abc"; @@ -277,5 +315,61 @@ public void InWithCombinationWithFieldUsageUpdate() trx.Complete(); } } + + private void CheckSetFromSelectSupported() + { + if (Domain.StorageProviderInfo.ProviderName == WellKnown.Provider.MySql) { + throw new IgnoreException("Test is inconclusive for current provider"); + } + } + + private void CheckSetFromSelectUnsupported() + { + if (Domain.StorageProviderInfo.ProviderName != WellKnown.Provider.MySql) { + throw new IgnoreException("Test is inconclusive for current provider"); + } + } + + private void CheckOneByOneSetApplication() + { + if (Domain.StorageProviderInfo.ProviderName != WellKnown.Provider.MySql) { + throw new IgnoreException("Test is inconclusive for current provider"); + } + } + + private void CheckGroupSetApplication() + { + if (Domain.StorageProviderInfo.ProviderName == WellKnown.Provider.MySql) { + throw new IgnoreException("Test is inconclusive for current provider"); + } + } + + private DateTime FixDateTimeForPK(DateTime origin) + { + var currentProvider = Domain.StorageProviderInfo.ProviderName; + + long? divider; + switch (currentProvider) { + case WellKnown.Provider.MySql: + divider = 10000000; + break; + case WellKnown.Provider.Firebird: + divider = 1000; + break; + case WellKnown.Provider.PostgreSql: + divider = 10; + break; + default: + divider = (long?) null; + break; + } + + if (!divider.HasValue) { + return origin; + } + var ticks = origin.Ticks; + var newTicks = ticks - (ticks % divider.Value); + return new DateTime(newTicks); + } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs index 39a5a4bf89..57e0a0b528 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs @@ -10,468 +10,487 @@ internal class ReferenceFields : AutoBuildTest [Test] public void InsertClientSideReferenceField() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar(session); - var foo = new Foo(session); + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar(session); + var foo = new Foo(session); - Key key = session.Query.Insert(() => new Foo(session) {Bar = bar, Name = "test"}); - var foo2 = session.Query.Single(key); - Assert.That(foo2.Bar, Is.EqualTo(bar)); + var key = session.Query.Insert(() => new Foo(session) { Bar = bar, Name = "test" }); + var foo2 = session.Query.Single(key); + Assert.That(foo2.Bar, Is.EqualTo(bar)); - key = session.Query.Insert(() => new Foo(session) {Bar = null, Name = "test1"}); - foo2 = session.Query.Single(key); - Assert.That(foo2.Bar, Is.Null); + key = session.Query.Insert(() => new Foo(session) { Bar = null, Name = "test1" }); + foo2 = session.Query.Single(key); + Assert.That(foo2.Bar, Is.Null); - trx.Complete(); - } + trx.Complete(); } } [Test] public void InsertClientSideReferenceField2() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar2(session, DateTime.Now, Guid.NewGuid()); - var foo = new Foo2(session, 1, "1"); + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar2(session, FixDateTimeForPK(DateTime.Now), Guid.NewGuid()); + var foo = new Foo2(session, 1, "1"); - Key key = session.Query.Insert(() => new Foo2(null, 0, null) {Bar = bar, Id = 0, Id2 = "test", Name = "test"}); - var foo2 = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo2.Bar)); + var key = session.Query.Insert(() => new Foo2(null, 0, null) { Bar = bar, Id = 0, Id2 = "test", Name = "test" }); + var foo2 = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo2.Bar)); - key = session.Query.Insert(() => new Foo2(null, 0, null) {Bar = null, Id = 0, Id2 = "test1", Name = "test1"}); - foo2 = session.Query.Single(key); - Assert.That(foo2.Bar, Is.Null); + key = session.Query.Insert(() => new Foo2(null, 0, null) { Bar = null, Id = 0, Id2 = "test1", Name = "test1" }); + foo2 = session.Query.Single(key); + Assert.That(foo2.Bar, Is.Null); - trx.Complete(); - } + trx.Complete(); } } [Test] public void UpdateServerSideReferenceField() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar(session); - var foo = new Foo(session); - var bara = new Bar(session); - session.SaveChanges(); - Assert.That(foo.Bar, Is.Null); - int one = 1; - - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.Single(Key.Create(Domain, typeof (Bar), 1))). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.Single(Key.Create(Domain, 1))). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), () => session.Query.All().Set(a => a.Bar, a => session.Query.Single(1)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, typeof (Bar), 1))).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, 1))).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => session.Query.All().Set(a => a.Bar, a => session.Query.SingleOrDefault(1)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id==one).First()). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => session.Query.All().Set(a => a.Bar, a => session.Query.All().First(b => b.Id==1)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.All().Where(b => b.Id==1).FirstOrDefault()).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().FirstOrDefault(b => b.Id==1)). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id==1).Single()). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => session.Query.All().Set(a => a.Bar, a => session.Query.All().Single(b => b.Id==1)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.All().Where(b => b.Id==1).SingleOrDefault()).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().SingleOrDefault(b => b.Id==1)). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar(session); + var foo = new Foo(session); + var bara = new Bar(session); + session.SaveChanges(); + Assert.That(foo.Bar, Is.Null); + var one = 1; + + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.Single(Key.Create(Domain, typeof(Bar), 1))). + Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.Single(Key.Create(Domain, 1))). + Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), () => session.Query.All().Set(a => a.Bar, a => session.Query.Single(1)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, typeof(Bar), 1))).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, 1))).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => session.Query.All().Set(a => a.Bar, a => session.Query.SingleOrDefault(1)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id == one).First()). + Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => session.Query.All().Set(a => a.Bar, a => session.Query.All().First(b => b.Id == 1)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.All().Where(b => b.Id == 1).FirstOrDefault()).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().FirstOrDefault(b => b.Id == 1)). + Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id == 1).Single()). + Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => session.Query.All().Set(a => a.Bar, a => session.Query.All().Single(b => b.Id == 1)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.All().Where(b => b.Id == 1).SingleOrDefault()).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().SingleOrDefault(b => b.Id == 1)). + Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + trx.Complete(); } } [Test] public void InsertServerSideReferenceField() { - using (Session session = Domain.OpenSession()) - { - using (TransactionScope trx = session.OpenTransaction()) - { - var bar = new Bar(session); - var foo1 = new Foo(session); - session.SaveChanges(); - Assert.That(foo1.Bar, Is.Null); - int one = 1; - Key key = null; - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = (Bar)session.Query.Single(Key.Create(Domain, typeof(Bar), 1)), Name = "test" }) - ); - var foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.Single(Key.Create(Domain, 1)), Name = "test1" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.Single(1), Name = "test2" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = (Bar)session.Query.SingleOrDefault(Key.Create(Domain, typeof(Bar), 1)), Name = "test3" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = null, Name = "test4" }) - ); - foo = session.Query.Single(key); - Assert.That(foo.Bar, Is.Null); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.SingleOrDefault(1), Name = "test5" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == one).First(), Name = "test6" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().First(b => b.Id == 1), Name = "test7" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == 1).FirstOrDefault(), Name = "test8" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().FirstOrDefault(b => b.Id == 1), Name = "test9" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == 1).Single(), Name = "test10" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Single(b => b.Id == 1), Name = "test11" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == 1).SingleOrDefault(), Name = "test12" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.AssertCommandCount( - Is.EqualTo(1), - () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().SingleOrDefault(b => b.Id == 1), Name = "test13" }) - ); - foo = session.Query.Single(key); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar(session); + var foo1 = new Foo(session); + session.SaveChanges(); + Assert.That(foo1.Bar, Is.Null); + var one = 1; + Key key = null; + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = (Bar) session.Query.Single(Key.Create(Domain, typeof(Bar), 1)), Name = "test" }) + ); + var foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.Single(Key.Create(Domain, 1)), Name = "test1" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.Single(1), Name = "test2" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = (Bar) session.Query.SingleOrDefault(Key.Create(Domain, typeof(Bar), 1)), Name = "test3" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = null, Name = "test4" }) + ); + foo = session.Query.Single(key); + Assert.That(foo.Bar, Is.Null); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.SingleOrDefault(1), Name = "test5" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == one).First(), Name = "test6" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().First(b => b.Id == 1), Name = "test7" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == 1).FirstOrDefault(), Name = "test8" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().FirstOrDefault(b => b.Id == 1), Name = "test9" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == 1).Single(), Name = "test10" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Single(b => b.Id == 1), Name = "test11" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().Where(b => b.Id == 1).SingleOrDefault(), Name = "test12" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + session.AssertCommandCount( + Is.EqualTo(1), + () => key = session.Query.Insert(() => new Foo(session) { Bar = session.Query.All().SingleOrDefault(b => b.Id == 1), Name = "test13" }) + ); + foo = session.Query.Single(key); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + trx.Complete(); } } [Test] public void UpdateServerSideReferenceField2() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - DateTime date = DateTime.Now; - Guid id = Guid.NewGuid(); - var bar = new Bar2(session, date, id); - var foo = new Foo2(session, 1, "1"); - var bar2 = new Bar2(session, DateTime.Now, Guid.NewGuid()); - session.SaveChanges(); - Assert.That(foo.Bar, Is.Null); - - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.Single(Key.Create(Domain, typeof (Bar2), date, id))).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.Single(Key.Create(Domain, date, id))).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => session.Query.All().Set(a => a.Bar, a => session.Query.Single(date, id)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, typeof (Bar2), date, id))).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, date, id))).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => session.Query.All().Set(a => a.Bar, a => session.Query.SingleOrDefault(date, id)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id2==id).First()). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().First(b => b.Id2==id)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.All().Where(b => b.Id2==id).FirstOrDefault()).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().FirstOrDefault(b => b.Id2==id)). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id2==id).Single()). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().Single(b => b.Id2==id)).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set( - a => a.Bar, a => session.Query.All().Where(b => b.Id2==id).SingleOrDefault()).Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.AssertCommandCount( - Is.EqualTo(1), - () => - session.Query.All().Set(a => a.Bar, a => session.Query.All().SingleOrDefault(b => b.Id2==id)). - Update()); - Assert.That(bar, Is.EqualTo(foo.Bar)); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var date = FixDateTimeForPK(DateTime.Now); + var id = Guid.NewGuid(); + var bar = new Bar2(session, date, id); + var foo = new Foo2(session, 1, "1"); + var bar2 = new Bar2(session, DateTime.Now, Guid.NewGuid()); + session.SaveChanges(); + Assert.That(foo.Bar, Is.Null); + + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.Single(Key.Create(Domain, typeof(Bar2), date, id))).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.Single(Key.Create(Domain, date, id))).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => session.Query.All().Set(a => a.Bar, a => session.Query.Single(date, id)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, typeof(Bar2), date, id))).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.SingleOrDefault(Key.Create(Domain, date, id))).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => session.Query.All().Set(a => a.Bar, a => session.Query.SingleOrDefault(date, id)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id2 == id).First()) + .Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().First(b => b.Id2 == id)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.All().Where(b => b.Id2 == id).FirstOrDefault()).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().FirstOrDefault(b => b.Id2 == id)) + .Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().Where(b => b.Id2 == id).Single()) + .Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().Single(b => b.Id2 == id)).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set( + a => a.Bar, a => session.Query.All().Where(b => b.Id2 == id).SingleOrDefault()).Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + session.AssertCommandCount( + Is.EqualTo(1), + () => + session.Query.All().Set(a => a.Bar, a => session.Query.All().SingleOrDefault(b => b.Id2 == id)) + .Update()); + Assert.That(bar, Is.EqualTo(foo.Bar)); + trx.Complete(); } } [Test] public void UpdateClientSideReferenceField() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar(session); - var foo = new Foo(session); - var bar2 = new Bar(session); - session.Query.All().Set(a => a.Bar, bar).Update(); - Assert.That(bar, Is.EqualTo(foo.Bar)); - session.Query.All().Set(a => a.Bar, (Bar) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.Query.All().Update(a => new Foo(session) {Bar = bar}); - Assert.That(bar, Is.EqualTo(foo.Bar)); - session.Query.All().Update(a => new Foo(session) {Bar = null}); - Assert.That(foo.Bar, Is.Null); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar(session); + var foo = new Foo(session); + var bar2 = new Bar(session); + _ = session.Query.All().Set(a => a.Bar, bar).Update(); + Assert.That(bar, Is.EqualTo(foo.Bar)); + _ = session.Query.All().Set(a => a.Bar, (Bar) null).Update(); + Assert.That(foo.Bar, Is.Null); + _ = session.Query.All().Update(a => new Foo(session) { Bar = bar }); + Assert.That(bar, Is.EqualTo(foo.Bar)); + _ = session.Query.All().Update(a => new Foo(session) { Bar = null }); + Assert.That(foo.Bar, Is.Null); + trx.Complete(); } } [Test] public void UpdateClientSideReferenceField2() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar2(session, DateTime.Now, Guid.NewGuid()); - var foo = new Foo2(session, 1, "1"); - var bar2 = new Bar2(session, DateTime.Now, Guid.NewGuid()); - session.Query.All().Set(a => a.Bar, bar).Update(); - Assert.That(bar, Is.EqualTo(foo.Bar)); - session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); - Assert.That(foo.Bar, Is.Null); - session.Query.All().Update(a => new Foo2(null, 0, null) {Bar = bar}); - Assert.That(bar, Is.EqualTo(foo.Bar)); - session.Query.All().Update(a => new Foo2(null, 0, null) {Bar = null}); - Assert.That(foo.Bar, Is.Null); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar2(session, FixDateTimeForPK(DateTime.Now), Guid.NewGuid()); + var foo = new Foo2(session, 1, "1"); + var bar2 = new Bar2(session, DateTime.Now, Guid.NewGuid()); + _ = session.Query.All().Set(a => a.Bar, bar).Update(); + Assert.That(bar, Is.EqualTo(foo.Bar)); + _ = session.Query.All().Set(a => a.Bar, (Bar2) null).Update(); + Assert.That(foo.Bar, Is.Null); + _ = session.Query.All().Update(a => new Foo2(null, 0, null) { Bar = bar }); + Assert.That(bar, Is.EqualTo(foo.Bar)); + _ = session.Query.All().Update(a => new Foo2(null, 0, null) { Bar = null }); + Assert.That(foo.Bar, Is.Null); + trx.Complete(); } } + + private DateTime FixDateTimeForPK(DateTime origin) + { + var currentProvider = Domain.StorageProviderInfo.ProviderName; + + long? divider; + switch (currentProvider) { + case WellKnown.Provider.MySql: + divider = 10000000; + break; + case WellKnown.Provider.Firebird: + divider = 1000; + break; + case WellKnown.Provider.PostgreSql: + divider = 10; + break; + default: + divider = (long?) null; + break; + } + + if (!divider.HasValue) { + return origin; + } + var ticks = origin.Ticks; + var newTicks = ticks - (ticks % divider.Value); + return new DateTime(newTicks); + } } } \ No newline at end of file From fbd28b75de29908666d9a3b4da56e97a61344c4c Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 18:55:34 +0500 Subject: [PATCH 02/71] Make test work not for SQL Server but for all RDBMSs --- .../Tests/Reprocessing.cs | 38 +++++++++++++------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs b/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs index e0640bdc83..ba7741bb5e 100644 --- a/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs +++ b/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs @@ -14,6 +14,8 @@ namespace Xtensive.Orm.Reprocessing.Tests { public class Reprocessing : AutoBuildTest { + private bool treatNullAsUniqueValue; + private int Bar2Count() { return Domain.Execute(session => Queryable.Count(session.Query.All())); @@ -189,6 +191,12 @@ public Context(Domain domain) } } + public override void SetUp() + { + base.SetUp(); + treatNullAsUniqueValue = Domain.StorageProviderInfo.ProviderName == WellKnown.Provider.SqlServer; + } + [Test] public void Test() { @@ -320,30 +328,36 @@ public void Test() [Test] public void UniqueConstraintViolationExceptionPrimary() { - int i = 0; + var i = 0; Domain.WithStrategy(ExecuteActionStrategy.HandleUniqueConstraintViolation).Execute( session => { - new Foo(session, i); + _ = new Foo(session, i); i++; - if (i < 5) - new Foo(session, i); - } - ); - Assert.That(i, Is.EqualTo(5)); + if (i < 5) { + _ = new Foo(session, i); + } + }); + if (treatNullAsUniqueValue) { + Assert.That(i, Is.EqualTo(5)); + } + else { + Assert.That(i, Is.EqualTo(1)); + } } [Test] public void UniqueConstraintViolationExceptionUnique() { - int i = 0; - bool b = false; + var i = 0; + var b = false; ExecuteActionStrategy.HandleUniqueConstraintViolation.Error += (sender, args) => b = true; Domain.WithStrategy(ExecuteActionStrategy.HandleUniqueConstraintViolation).Execute( session => { - new Foo(session) {Name = "test"}; + _ = new Foo(session) { Name = "test" }; i++; - if (i < 5) - new Foo(session) {Name = "test"}; + if (i < 5) { + _ = new Foo(session) { Name = "test" }; + } }); Assert.That(i, Is.EqualTo(5)); Assert.That(b, Is.True); From 653b9feb7b4f00d9a225147765c8257c299fe564 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 18:57:26 +0500 Subject: [PATCH 03/71] Add new error codes for UniqueConstraintViolation New codes have the same meaning so should be treated as UniqueConstraintViolation, not as Unknown --- Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Driver.cs | 7 ++++--- Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/Driver.cs | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Driver.cs b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Driver.cs index 58798f7293..ffef452dba 100644 --- a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Driver.cs +++ b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Driver.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Csaba Beer // Created: 2011.01.08 @@ -33,6 +33,7 @@ public override SqlExceptionType GetExceptionType(System.Exception exception) case 335544347: // exactly: validation error for column case 335544558: // exactly: operation violates check constraint return SqlExceptionType.CheckConstraintViolation; + case 335544349: case 335544665: return SqlExceptionType.UniqueConstraintViolation; case 335544466: diff --git a/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/Driver.cs b/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/Driver.cs index 1461d31f8c..6b0bfe3643 100644 --- a/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/Driver.cs +++ b/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/Driver.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Malisa Ncube // Created: 2011.02.25 @@ -37,6 +37,7 @@ public override SqlExceptionType GetExceptionType(Exception exception) return SqlExceptionType.ConnectionError; case 1149: return SqlExceptionType.SyntaxError; + case 1062: case 1169: return SqlExceptionType.UniqueConstraintViolation; case 1205: From f7c4d6e0c10dc9c8d9ed63926c3283e7edfc92d1 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 19:43:01 +0500 Subject: [PATCH 04/71] Change Chinook model based tests - Added indexes to the model - Changed filters for .Single() to actually return single value and not ruin tests - Certain First/FirstOrDefault() and Single/SingleOrDefault() tests were improved by adding new Asserts to them. - Some tests were ignored for MySql because they don't suppose to run against it - Split SelectStringContains() test into the one for case-sensitive and another for case-insensitive databases to prevent false fails --- Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs | 19 +- .../Linq/FirstSingleTest.cs | 54 +++-- Orm/Xtensive.Orm.Tests/Linq/LockTest.cs | 87 +++++--- .../Linq/NestedCollectionsTest.cs | 87 +++++--- Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs | 211 ++++++++++-------- Orm/Xtensive.Orm.Tests/ObjectModel/Chinook.cs | 15 +- 6 files changed, 282 insertions(+), 191 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs b/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs index 26c45557c5..928642f3a6 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 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 // Created: 2009.04.02 @@ -22,10 +22,10 @@ public class EntitySetTest : ChinookDOModelTest public void EntitySetAnonymousTest() { var result = Session.Query.All() - .Select(c => new {InvoicesFiled = c.Invoices}); + .Select(c => new { InvoicesFiled = c.Invoices }); var expected = Session.Query.All() .ToList() - .Select(c => new {InvoicesFiled = c.Invoices }); + .Select(c => new { InvoicesFiled = c.Invoices }); Assert.AreEqual(0, expected.Except(result).Count()); QueryDumper.Dump(result); } @@ -34,11 +34,11 @@ public void EntitySetAnonymousTest() public void EntitySetSelectManyAnonymousTest() { var result = Session.Query.All() - .Select(c => new {InvoicesFiled = c.Invoices }) + .Select(c => new { InvoicesFiled = c.Invoices }) .SelectMany(i => i.InvoicesFiled); var expected = Session.Query.All() .ToList() - .Select(c => new {InvoicesFiled = c.Invoices }) + .Select(c => new { InvoicesFiled = c.Invoices }) .SelectMany(i => i.InvoicesFiled); Assert.AreEqual(0, expected.Except(result).Count()); QueryDumper.Dump(result); @@ -51,8 +51,9 @@ public void EntitySetSelectTest() var expected = Session.Query.All().AsEnumerable().OrderBy(c=>c.CustomerId).Select(c => c.Invoices).ToList(); Assert.Greater(result.Count, 0); Assert.AreEqual(expected.Count, result.Count); - for (int i = 0; i < result.Count; i++) + for (var i = 0; i < result.Count; i++) { Assert.AreSame(expected[i], result[i]); + } } [Test] @@ -124,7 +125,7 @@ join e in Session.Query.All() on i.DesignatedEmployee equals e private static Customer GetCustomer() { - return Session.Demand().Query.All().Where(c => c.FirstName=="Luis").Single(); + return Session.Demand().Query.All().Where(c => c.FirstName == "Aaron").Single(); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs b/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs index b164e4d015..ad382a65c5 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.02.04 @@ -51,7 +51,7 @@ public void Length3Test() .Select(order => order.BillingAddress.City) .SingleOrDefault() .Length > 0); - Assert.Throws(() => QueryDumper.Dump(customers)); + _ = Assert.Throws(() => QueryDumper.Dump(customers)); } [Test] @@ -64,14 +64,14 @@ public void FirstTest() [Test] public void FirstPredicateTest() { - var customer = Session.Query.All().First(c => c.FirstName=="Luis"); + var customer = Session.Query.All().First(c => c.FirstName == "Luis"); Assert.IsNotNull(customer); } [Test] public void WhereFirstTest() { - var customer = Session.Query.All().Where(c => c.FirstName=="Luis").First(); + var customer = Session.Query.All().Where(c => c.FirstName == "Luis").First(); Assert.IsNotNull(customer); } @@ -85,14 +85,23 @@ public void FirstOrDefaultTest() [Test] public void FirstOrDefaultPredicateTest() { - Session.Query.All().FirstOrDefault(c => c.FirstName=="Luis"); + var customer = Session.Query.All().FirstOrDefault(c => c.FirstName == "Luis"); + Assert.IsNotNull(customer); + customer = Session.Query.All().FirstOrDefault(c => c.FirstName == "Aaron"); + Assert.IsNotNull(customer); + customer = Session.Query.All().FirstOrDefault(c => c.FirstName == "ThereIsNoSuchFirstName"); + Assert.IsNull(customer); } [Test] public void WhereFirstOrDefaultTest() { - var customer = Session.Query.All().Where(c => c.FirstName=="Luis").FirstOrDefault(); + var customer = Session.Query.All().Where(c => c.FirstName == "Luis").FirstOrDefault(); Assert.IsNotNull(customer); + customer = Session.Query.All().Where(c => c.FirstName == "Aaron").FirstOrDefault(); + Assert.IsNotNull(customer); + customer = Session.Query.All().Where(c => c.FirstName == "ThereIsNoSuchFirstName").FirstOrDefault(); + Assert.IsNull(customer); } [Test] @@ -104,15 +113,19 @@ public void SingleTest() [Test] public void SinglePredicateTest() { - var customer = Session.Query.All().Single(c => c.FirstName=="Luis"); + var customer = Session.Query.All().Single(c => c.FirstName == "Aaron"); Assert.IsNotNull(customer); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Luis").Single()); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "ThereIsNoSuchFirstName").Single()); } [Test] public void WhereSingleTest() { - var customer = Session.Query.All().Where(c => c.FirstName=="Luis").Single(); + var customer = Session.Query.All().Where(c => c.FirstName == "Aaron").Single(); Assert.IsNotNull(customer); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Luis").Single()); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "ThereIsNoSuchFirstName").Single()); } [Test] @@ -124,15 +137,21 @@ public void SingleOrDefaultTest() [Test] public void SingleOrDefaultPredicateTest() { - var customer = Session.Query.All().SingleOrDefault(c => c.FirstName=="Luis"); + var customer = Session.Query.All().SingleOrDefault(c => c.FirstName == "Aaron"); Assert.IsNotNull(customer); + _ = Assert.Throws(() => Session.Query.All().SingleOrDefault(c => c.FirstName == "Luis")); + customer = Session.Query.All().SingleOrDefault(c => c.FirstName == "ThereIsNoSuchFirstName"); + Assert.IsNull(customer); } [Test] public void WhereSingleOrDefaultTest() { - var customer = Session.Query.All().Where(c => c.FirstName=="Luis").SingleOrDefault(); + var customer = Session.Query.All().Where(c => c.FirstName == "Aaron").SingleOrDefault(); Assert.IsNotNull(customer); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Luis").SingleOrDefault()); + customer = Session.Query.All().Where(c => c.FirstName == "ThereIsNoSuchFirstName").SingleOrDefault(); + Assert.IsNull(customer); } [Test] @@ -145,7 +164,7 @@ public void SelectFirstTest() select new { Invoice = i, MaxOrder = invoiceLines - .Where(il => il.Invoice==i) + .Where(il => il.Invoice == i) .OrderByDescending(il => il.UnitPrice * il.Quantity) .First() .Invoice @@ -206,16 +225,17 @@ public void SubquerySingleExpectedException1Test() public void SubquerySingleExpectedException2Test() { Require.ProviderIsNot(StorageProvider.SqlServerCe); - bool exceptionThrown = false; + var exceptionThrown = false; var result = Session.Query.All().Where(c => c.Invoices.Count > 0).Select(c => c.Invoices.Single()); try { - result.ToList(); + _ = result.ToList(); } catch { exceptionThrown = true; } - if (!exceptionThrown) + if (!exceptionThrown) { Assert.Fail("Exception was not thrown."); + } } [Test] @@ -281,7 +301,7 @@ public void ComplexSubquerySelectFirstTest() var result = Session.Query.All() .Where(p => p.Tracks.Any()) .Select(p => p.Tracks.First()) - .Select(t => new {Track = t, t.Name, t.Album}); + .Select(t => new { Track = t, t.Name, t.Album }); var list = result.ToList(); Assert.AreEqual(playlistCount, list.Count); } diff --git a/Orm/Xtensive.Orm.Tests/Linq/LockTest.cs b/Orm/Xtensive.Orm.Tests/Linq/LockTest.cs index e67cacef10..05f2006038 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/LockTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/LockTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2009.08.25 @@ -29,6 +29,7 @@ protected override void CheckRequirements() [Test] public void UpdateLockThrowTest() { + Require.ProviderIsNot(StorageProvider.MySql); var catchedException = ExecuteConcurrentQueries(LockMode.Update, LockBehavior.Wait, LockMode.Update, LockBehavior.ThrowIfLocked); // Assert.AreEqual(typeof(StorageException), catchedException.GetType()); @@ -37,21 +38,22 @@ public void UpdateLockThrowTest() [Test] public void CachingTest() { - List trackIds = new List(32); + var trackIds = new List(32); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - for (var i = 0; i < trackIds.Capacity; i++) - trackIds.Add(new AudioTrack() {Name = "SomeTrack"}.TrackId); + for (var i = 0; i < trackIds.Capacity; i++) { + trackIds.Add(new AudioTrack() { Name = "SomeTrack" }.TrackId); + } transaction.Complete(); } - ConcurrentBag> results = new ConcurrentBag>(); + var results = new ConcurrentBag>(); var source = trackIds.Select(t => new {PId = t, Bag = results}); - Parallel.ForEach( + _ = Parallel.ForEach( source, - new ParallelOptions {MaxDegreeOfParallelism = 4}, + new ParallelOptions { MaxDegreeOfParallelism = 4 }, (sourceItem, state, currentItteration) => { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { @@ -62,8 +64,9 @@ public void CachingTest() }; session.Events.DbCommandExecuting += handler; - if (trackToLock!=null) + if (trackToLock != null) { trackToLock.Lock(LockMode.Update, LockBehavior.Wait); + } session.Events.DbCommandExecuting -= handler; } @@ -71,7 +74,7 @@ public void CachingTest() try { Assert.That(results.Count, Is.EqualTo(trackIds.Capacity)); - Assert.That(results.All(t => t.First==t.Second), Is.True); + Assert.That(results.All(t => t.First == t.Second), Is.True); } finally { using (var session = Domain.OpenSession()) @@ -86,9 +89,11 @@ public void CachingTest() [Test] public void LockNewlyCreatedEntity() { - var track = new AudioTrack() {Name = "SomeTrack"}; - using (Session.DisableSaveChanges()) + Require.ProviderIsNot(StorageProvider.MySql); + var track = new AudioTrack() { Name = "SomeTrack" }; + using (Session.DisableSaveChanges()) { track.Lock(LockMode.Exclusive, LockBehavior.ThrowIfLocked); + } } [Test] @@ -99,15 +104,16 @@ public void UpdateLockSkipTest() var expected = Session.Query.All().Where(c => c.Key == key) .Lock(LockMode.Update, LockBehavior.Wait).ToList(); Exception catchedException = null; - int countAfterSkip = 0; + var countAfterSkip = 0; var secondThread = new Thread(() => { try { using (var session = Domain.OpenSession()) - using (session.OpenTransaction()) + using (session.OpenTransaction()) { countAfterSkip = session.Query.All() .Where(c => c.Key == key) .Lock(LockMode.Update, LockBehavior.Skip) .ToList().Count; + } } catch(Exception e) { catchedException = e; @@ -115,8 +121,10 @@ public void UpdateLockSkipTest() }); secondThread.Start(); secondThread.Join(); - if (catchedException != null) + if (catchedException != null) { throw catchedException; + } + Assert.AreEqual(0, countAfterSkip); } @@ -141,7 +149,7 @@ public void ExclusiveLockThrowTest() [Test] public void ShareLockTest() { - Require.ProviderIs(StorageProvider.SqlServer | StorageProvider.PostgreSql); + Require.ProviderIs(StorageProvider.SqlServer | StorageProvider.PostgreSql | StorageProvider.MySql); var catchedException = ExecuteConcurrentQueries(LockMode.Shared, LockBehavior.ThrowIfLocked, LockMode.Shared, LockBehavior.ThrowIfLocked); Assert.IsNull(catchedException); @@ -152,7 +160,7 @@ public void LockAfterJoinTest() { Require.ProviderIs(StorageProvider.SqlServer | StorageProvider.PostgreSql); var customerKey = Session.Query.All().First().Key; - var invoiceKey = Session.Query.All().Where(i => i.Customer.Key==customerKey).First().Key; + var invoiceKey = Session.Query.All().Where(i => i.Customer.Key == customerKey).First().Key; Exception firstThreadException = null; Exception result = null; var firstEvent = new ManualResetEvent(false); @@ -161,31 +169,32 @@ public void LockAfterJoinTest() try { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - session.Query.All().Where(c => c.Key == customerKey) + _ = session.Query.All().Where(c => c.Key == customerKey) .Join(session.Query.All().Where(i => i.Key == invoiceKey), c => c, i => i.Customer, (c, i) => c) .Lock(LockMode.Update, LockBehavior.Wait).ToList(); - secondEvent.Set(); - firstEvent.WaitOne(); + _ = secondEvent.Set(); + _ = firstEvent.WaitOne(); } } catch(Exception e) { firstThreadException = e; - secondEvent.Set(); + _ = secondEvent.Set(); return; } }); firstThread.Start(); - secondEvent.WaitOne(); + _ = secondEvent.WaitOne(); var secondException = ExecuteQueryAtSeparateThread(s => s.Query.All() - .Where(c => c.Key==customerKey).Lock(LockMode.Update, LockBehavior.ThrowIfLocked)); + .Where(c => c.Key == customerKey).Lock(LockMode.Update, LockBehavior.ThrowIfLocked)); Assert.AreEqual(typeof(StorageException), secondException.GetType()); var thirdException = ExecuteQueryAtSeparateThread(s => s.Query.All() - .Where(i => i.Key==invoiceKey).Lock(LockMode.Update, LockBehavior.ThrowIfLocked)); + .Where(i => i.Key == invoiceKey).Lock(LockMode.Update, LockBehavior.ThrowIfLocked)); Assert.AreEqual(typeof(StorageException), thirdException.GetType()); - firstEvent.Set(); + _ = firstEvent.Set(); firstThread.Join(); - if (firstThreadException != null) + if (firstThreadException != null) { throw firstThreadException; + } } [Test] @@ -198,10 +207,12 @@ public void LockEntityTest() var catchedException = ExecuteQueryAtSeparateThread(s => s.Query.All().Where(c => c == customer).Lock(LockMode.Update, LockBehavior.ThrowIfLocked)); Assert.AreEqual(typeof(StorageException), catchedException.GetType()); + using (var session = Domain.OpenSession()) - using (session.OpenTransaction()) + using (session.OpenTransaction()) { AssertEx.Throws(() => session.Query.Single(customerKey).Lock(LockMode.Update, LockBehavior.ThrowIfLocked)); + } } private Exception ExecuteConcurrentQueries(LockMode lockMode0, LockBehavior lockBehavior0, @@ -216,36 +227,38 @@ private Exception ExecuteConcurrentQueries(LockMode lockMode0, LockBehavior lock try { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - session.Query.All().Where(c => c.Key == key).Lock(lockMode0, lockBehavior0).ToList(); - secondEvent.Set(); - firstEvent.WaitOne(); + _ = session.Query.All().Where(c => c.Key == key).Lock(lockMode0, lockBehavior0).ToList(); + _ = secondEvent.Set(); + _ = firstEvent.WaitOne(); } } catch(Exception e) { firstThreadException = e; - secondEvent.Set(); + _ = secondEvent.Set(); return; } }); firstThread.Start(); - secondEvent.WaitOne(); - if (firstThreadException != null) + _ = secondEvent.WaitOne(); + if (firstThreadException != null) { throw firstThreadException; + } + result = ExecuteQueryAtSeparateThread(s => s.Query.All() .Where(c => c.Key == key).Lock(lockMode1, lockBehavior1)); - firstEvent.Set(); + _ = firstEvent.Set(); firstThread.Join(); return result; } - private Exception ExecuteQueryAtSeparateThread(Func> query) + private Exception ExecuteQueryAtSeparateThread(Func> query) { Exception result = null; var thread = new Thread(() => { try { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - query.Invoke(session).ToList(); + _ = query.Invoke(session).ToList(); } } catch(Exception e) { diff --git a/Orm/Xtensive.Orm.Tests/Linq/NestedCollectionsTest.cs b/Orm/Xtensive.Orm.Tests/Linq/NestedCollectionsTest.cs index 47ce1f1853..763e53feaf 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/NestedCollectionsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/NestedCollectionsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 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 // Created: 2009.04.16 @@ -41,14 +41,16 @@ from c in Session.Query.All() select new { Customer = c, Invoices = c.Invoices - .Select(i => new {Invoice = i, InvoiceLines = i.InvoiceLines}) + .Select(i => new { Invoice = i, InvoiceLines = i.InvoiceLines }) }; Assert.That(result, Is.Not.Empty); - foreach (var a in result) - foreach (var b in a.Invoices) + foreach (var a in result) { + foreach (var b in a.Invoices) { foreach (var il in b.InvoiceLines) { } + } + } } [Test] @@ -66,7 +68,9 @@ public void SubqueryWithThisTest() public void SelectOtherParameterTest() { Require.ProviderIsNot(StorageProvider.SqlServerCe); - var result = Session.Query.All().Take(5).Select(c => Session.Query.All().Select(i => c.Invoices.Count())); + var result = Session.Query.All() + .Take(5) + .Select(c => Session.Query.All().Select(i => c.Invoices.Count())); Assert.That(result.ToList(), Is.Not.Empty); } @@ -96,7 +100,7 @@ public void SelectDoubleNestedTest() [Test] public void ComplexSubqueryTest() { - Require.ProviderIsNot(StorageProvider.SqlServerCe); + Require.ProviderIsNot(StorageProvider.SqlServerCe | StorageProvider.MySql); var result = Session.Query.All() .Take(2) .Select(c => Session.Query.All() @@ -113,7 +117,7 @@ public void ComplexSubqueryTest() public void SelectNestedWithCorrelationTest() { var result = Session.Query.All() - .Select(c => Session.Query.All().Where(i => i.Customer==c)) + .Select(c => Session.Query.All().Where(i => i.Customer == c)) .Select(qi => qi); Assert.That(result, Is.Not.Empty); Assert.AreEqual(numberOfInvoices, Count(result)); @@ -124,7 +128,7 @@ public void SelectNestedWithAggregateTest() { Require.ProviderIsNot(StorageProvider.SqlServerCe | StorageProvider.Oracle); var result = Session.Query.All() - .Select(c => Session.Query.All().Where(i => i.Customer==c).Count()); + .Select(c => Session.Query.All().Where(i => i.Customer == c).Count()); Assert.That(result, Is.Not.Empty); QueryDumper.Dump(result); } @@ -134,7 +138,7 @@ public void SelectAnonymousTest() { var result = Session.Query.All() .Take(10) - .Select(c => new {Invoices = Session.Query.All().Take(10)}); + .Select(c => new { Invoices = Session.Query.All().Take(10) }); Assert.That(result, Is.Not.Empty); QueryDumper.Dump(result); } @@ -143,7 +147,7 @@ public void SelectAnonymousTest() public void SubqueryAsQuerySourceTest() { var result = Session.Query.All() - .Select(c => Session.Query.All().Where(i => i.Customer==c)); + .Select(c => Session.Query.All().Where(i => i.Customer == c)); Assert.That(result, Is.Not.Empty); foreach (var invoices in result) { var subQueryCount = invoices.Count(); @@ -155,8 +159,8 @@ public void SelectTwoCollectionsTest() { var result = Session.Query.All() .Select(i => new { - Customers = Session.Query.All().Where(c => c==i.Customer), - Employees = Session.Query.All().Where(e => e==i.DesignatedEmployee) + Customers = Session.Query.All().Where(c => c == i.Customer), + Employees = Session.Query.All().Where(e => e == i.DesignatedEmployee) }) .Select(os => os); var list = result.ToList(); @@ -198,7 +202,7 @@ public void SelectDoubleNestedSelectManyTest() public void SelectNestedWithCorrelationSelectManyTest() { var result = Session.Query.All() - .Select(c => Session.Query.All().Where(i => i.Customer==c)) + .Select(c => Session.Query.All().Where(i => i.Customer == c)) .SelectMany(i => i); Assert.That(result, Is.Not.Empty); Assert.AreEqual(numberOfInvoices, Count(result)); @@ -208,7 +212,7 @@ public void SelectNestedWithCorrelationSelectManyTest() public void SelectNestedWithCorrelationSelectMany2Test() { var result = Session.Query.All() - .Select(c => Session.Query.All().Where(i => i.Customer==c)) + .Select(c => Session.Query.All().Where(i => i.Customer == c)) .SelectMany(i => i.Select(x => x)); Assert.That(result, Is.Not.Empty); Assert.AreEqual(numberOfInvoices, Count(result)); @@ -218,7 +222,10 @@ public void SelectNestedWithCorrelationSelectMany2Test() public void SelectAnonymousSelectMany1Test() { var result = Session.Query.All() - .Select(c => new {Customer = c, Invoices = Session.Query.All().Where(i => i.Customer==c)}) + .Select(c => new { + Customer = c, + Invoices = Session.Query.All().Where(i => i.Customer == c) + }) .SelectMany(i => i.Invoices); Assert.That(result, Is.Not.Empty); Assert.AreEqual(numberOfInvoices, result.ToList().Count); @@ -228,7 +235,7 @@ public void SelectAnonymousSelectMany1Test() public void SelectAnonymousSelectMany2Test() { var result = Session.Query.All() - .Select(c => new {Invoices = Session.Query.All().Take(10)}) + .Select(c => new { Invoices = Session.Query.All().Take(10) }) .SelectMany(i => i.Invoices); Assert.That(result, Is.Not.Empty); QueryDumper.Dump(result); @@ -238,7 +245,10 @@ public void SelectAnonymousSelectMany2Test() public void SelectAnonymousSubqueryTest() { var result = Session.Query.All() - .Select(c => new {Customer = c, Invoices = Session.Query.All()}) + .Select(c => new { + Customer = c, + Invoices = Session.Query.All() + }) .Select(i => i.Customer.Invoices); Assert.That(result, Is.Not.Empty); QueryDumper.Dump(result); @@ -247,8 +257,11 @@ public void SelectAnonymousSubqueryTest() [Test] public void SelectAnonymousSelectMany3Test() { - IQueryable result = Session.Query.All() - .Select(c => new {Customer = c, Invoices = Session.Query.All().Where(i => i.Customer==c)}) + var result = Session.Query.All() + .Select(c => new { + Customer = c, + Invoices = Session.Query.All().Where(i => i.Customer == c) + }) .SelectMany(a => a.Invoices.Select(i => a.Customer)); Assert.That(result, Is.Not.Empty); QueryDumper.Dump(result); @@ -258,8 +271,11 @@ public void SelectAnonymousSelectMany3Test() public void SelectAnonymousSelectMany4Test() { var result = Session.Query.All() - .Select(c => new {Customer = c, Invoices = Session.Query.All().Where(i => i.Customer==c)}) - .SelectMany(a => a.Invoices.Select(i => new {a.Customer, Invoice = i})); + .Select(c => new { + Customer = c, + Invoices = Session.Query.All().Where(i => i.Customer == c) + }) + .SelectMany(a => a.Invoices.Select(i => new { a.Customer, Invoice = i })); Assert.That(result, Is.Not.Empty); Assert.AreEqual(numberOfInvoices, result.ToList().Count); } @@ -268,7 +284,10 @@ public void SelectAnonymousSelectMany4Test() public void SelectAnonymousSelectMany5Test() { var result = Session.Query.All() - .Select(c => new {Customer = c, Invoices = Session.Query.All().Where(i => i.Customer==c)}) + .Select(c => new { + Customer = c, + Invoices = Session.Query.All().Where(i => i.Customer == c) + }) .SelectMany(a => a.Invoices.Select(i => a.Customer.FirstName)); Assert.That(result, Is.Not.Empty); QueryDumper.Dump(result); @@ -280,7 +299,7 @@ public void SubquerySimpleTest() var result = Session.Query.All() .Select(t => Session.Query.All()); Assert.That(result, Is.Not.Empty); - foreach (IQueryable queryable in result) { + foreach (var queryable in result) { QueryDumper.Dump(queryable); } } @@ -289,9 +308,9 @@ public void SubquerySimpleTest() public void SubqueryWhereTest() { var result = Session.Query.All() - .Select(t => Session.Query.All().Where(m => m==t.MediaType)); + .Select(t => Session.Query.All().Where(m => m == t.MediaType)); Assert.That(result, Is.Not.Empty); - foreach (IQueryable queryable in result) { + foreach (var queryable in result) { QueryDumper.Dump(queryable); } } @@ -311,10 +330,10 @@ public void SubqueryParametrizedFieldTest() public void SubqueryWithSelectTest() { var result = Session.Query.All() - .Select(t => Session.Query.All().Where(m => m==t.MediaType)) + .Select(t => Session.Query.All().Where(m => m == t.MediaType)) .Select(m => m); Assert.That(result, Is.Not.Empty); - foreach (IQueryable queryable in result) { + foreach (var queryable in result) { QueryDumper.Dump(queryable); } } @@ -344,12 +363,16 @@ private static int Count(IEnumerable result) var count = 0; bool? nested = null; foreach (var item in result) { - if (nested==null) + if (nested == null) { nested = item is IEnumerable; - if (nested.Value) + } + + if (nested.Value) { count += Count((IEnumerable) item); - else + } + else { count++; + } } return count; } diff --git a/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs b/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs index ef35e33042..61c956124e 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kochetov // Created: 2009.01.12 @@ -69,11 +69,11 @@ public void IndexerSimpleFieldTest() var qr = Session.Query.All(); - var filter = new Dictionary {{"Phone", "Test 718"}}; + var filter = new Dictionary { { "Phone", "Test 718" } }; foreach (var item in filter) { var pair = item; // This is important to use local variable - qr = qr.Where(customer => customer[pair.Key]==pair.Value); + qr = qr.Where(customer => customer[pair.Key] == pair.Value); } var list = qr.ToList(); @@ -114,7 +114,7 @@ public void IndexerStructureTest() [Test] public void IndexerError1Test() { - Assert.Throws(() => { + _ = Assert.Throws(() => { var result = Session.Query .All() .Select(customer => customer["Ph1one"]) @@ -125,10 +125,10 @@ public void IndexerError1Test() [Test] public void IndexerError2Test() { - Assert.Throws(() => { + _ = Assert.Throws(() => { var result = Session.Query .All() - .Where(invoice => invoice["Commission"]==invoice["Id"]) + .Where(invoice => invoice["Commission"] == invoice["Id"]) .ToList(); }); } @@ -143,7 +143,7 @@ public void StaticPropertyTest() customer .Invoices .Select(invoices => invoices.BillingAddress.State) - .FirstOrDefault()==StaticTestClass.Instance.Current); + .FirstOrDefault() == StaticTestClass.Instance.Current); QueryDumper.Dump(customers); } @@ -151,7 +151,7 @@ public void StaticPropertyTest() public void SelectEmployeeTest() { var result = Session.Query.All(); - var list = result.ToList(); + _ = result.ToList(); } [Test] @@ -179,7 +179,7 @@ public void SelectUsingContextTest() Assert.AreEqual(expectedCount, actualCount); Assert.AreEqual(expectedCount, list.Count); - var result = context.Customers.Where(c => context.Invoices.Count(i => i.Customer==c) > 5); + var result = context.Customers.Where(c => context.Invoices.Count(i => i.Customer == c) > 5); Assert.Greater(result.ToList().Count, 0); } @@ -202,7 +202,7 @@ public void NullJoinTest() public void AnonymousEntityTest() { var result = Session.Query.All() - .Select(album => new {Album = album}) + .Select(album => new { Album = album }) .Select(a => a.Album); QueryDumper.Dump(result); } @@ -211,7 +211,7 @@ public void AnonymousEntityTest() public void AnonymousEntityKeyTest() { var result = Session.Query.All() - .Select(album => new {Album = album}) + .Select(album => new { Album = album }) .Select(a => a.Album.Key); QueryDumper.Dump(result); } @@ -220,7 +220,7 @@ public void AnonymousEntityKeyTest() public void AnonymousEntityFieldTest() { var result = Session.Query.All() - .Select(album => new {Album = album}) + .Select(album => new { Album = album }) .Select(a => a.Album.Title); QueryDumper.Dump(result); } @@ -229,7 +229,7 @@ public void AnonymousEntityFieldTest() public void AnonymousEntityKeyFieldTest() { var result = Session.Query.All() - .Select(album => new {Album = album}) + .Select(album => new { Album = album }) .Select(a => a.Album.AlbumId); QueryDumper.Dump(result); } @@ -237,7 +237,7 @@ public void AnonymousEntityKeyFieldTest() [Test] public void OutOfHierarchy() { - Assert.Throws( () => { Assert.Greater(Session.Query.All().Count(), 0); }); + _ = Assert.Throws(() => Assert.Greater(Session.Query.All().Count(), 0)); } [Test] @@ -255,14 +255,15 @@ public void SimpleConstantTest() from t in tracks select 0; var list = result.ToList(); - foreach (var i in list) + foreach (var i in list) { Assert.AreEqual(0, i); + } } [Test] public void AnonymousColumn() { - var tracks = Session.Query.All().Select(t => new {t.Name}.Name); + var tracks = Session.Query.All().Select(t => new { t.Name }.Name); var list = tracks.ToList(); } @@ -275,13 +276,13 @@ public void AnonymousWithCalculatedColumnsTest() n2 = c.LastName.Length + c.FirstName.Length }); result = result.Where(i => i.n1 > 10); - result.ToList(); + _ = result.ToList(); } [Test] public void AnonymousParameterColumn() { - var param = new {ProductName = "name"}; + var param = new { ProductName = "name" }; var tracks = Session.Query.All().Select(t => param.ProductName); QueryDumper.Dump(tracks); } @@ -301,11 +302,12 @@ from t in tracks t.Name } orderby r.Name - where r.Method==method + where r.Method == method select r; var list = result.ToList(); - foreach (var i in list) + foreach (var i in list) { Assert.AreEqual(method, i.Method); + } } [Test] @@ -316,11 +318,12 @@ public void ConstantTest() from r in from t in tracks select 0 - where r==0 + where r == 0 select r; var list = result.ToList(); - foreach (var i in list) + foreach (var i in list) { Assert.AreEqual(0, i); + } } [Test] @@ -330,28 +333,32 @@ public void ConstantNullStringTest() var result = from t in tracks select (string) null; var list = result.ToList(); - foreach (var s in list) + foreach (var s in list) { Assert.AreEqual(null, s); + } } [Test] public void LocalTest() { - int x = 10; + var x = 10; var tracks = Session.Query.All(); var result = from r in from t in tracks select x - where r==x + where r == x select r; var list = result.ToList(); - foreach (var i in list) + foreach (var i in list) { Assert.AreEqual(10, i); + } + x = 20; list = result.ToList(); - foreach (var i in list) + foreach (var i in list) { Assert.AreEqual(20, i); + } } [Test] @@ -362,11 +369,12 @@ public void ColumnTest() from r in from t in tracks select t.Name - where r!=null + where r != null select r; var list = result.ToList(); - foreach (var s in list) + foreach (var s in list) { Assert.IsNotNull(s); + } } [Test] @@ -380,7 +388,7 @@ where r > 0 select r; var list = result.ToList(); var checkList = tracks.ToList().Select(t => t.UnitPrice * t.UnitPrice).ToList(); - list.SequenceEqual(checkList); + _ = list.SequenceEqual(checkList); } [Test] @@ -389,7 +397,7 @@ public void KeyTest() var tracks = Session.Query.All(); var result = tracks .Select(t => t.Key) - .Where(r => r!=null); + .Where(r => r != null); var list = result.ToList(); Assert.Greater(list.Count, 0); foreach (var k in list) { @@ -413,7 +421,7 @@ public void AnonymousTest() { var tracks = Session.Query.All(); var result = from t in tracks - select new {t.Name, t.UnitPrice}; + select new { t.Name, t.UnitPrice }; var list = result.ToList(); Assert.Greater(list.Count, 0); } @@ -423,7 +431,7 @@ public void AnonymousEmptyTest() { var tracks = Session.Query.All(); var result = from t in tracks - select new {}; + select new { }; var list = result.ToList(); Assert.Greater(list.Count, 0); } @@ -435,7 +443,7 @@ public void AnonymousCalculatedTest() var result = from r in from t in tracks - select new {t.Name, TotalPriceInStock = t.UnitPrice * t.UnitPrice} + select new { t.Name, TotalPriceInStock = t.UnitPrice * t.UnitPrice } where r.TotalPriceInStock > 0 select r; var list = result.ToList(); @@ -461,7 +469,7 @@ public void JoinedEntityTest() from r in from t in tracks select t.Album - where r.Title!=null + where r.Title != null select r; var list = result.ToList(); Assert.Greater(list.Count, 0); @@ -484,7 +492,7 @@ public void StructureTest() var result = from a in ( from i in invoices select i.Customer.Address) - where a.City!=null + where a.City != null select a.StreetAddress; var list = result.ToList(); Assert.Greater(list.Count, 0); @@ -506,8 +514,8 @@ public void AnonymousWithEntityTest() var result = from r in from t in tracks - select new {t.Name, Track = t} - where r.Track!=null + select new { t.Name, Track = t } + where r.Track != null select r; var list = result.ToList(); Assert.Greater(list.Count, 0); @@ -521,8 +529,8 @@ public void AnonymousNestedTest() var result = from r in from t in tracks - select new {t, Desc = new {t.Name, t.UnitPrice}} - where r.Desc.Name!=null + select new { t, Desc = new { t.Name, t.UnitPrice } } + where r.Desc.Name != null select r; var list = result.ToList(); Assert.Greater(list.Count, 0); @@ -534,9 +542,9 @@ public void NestedQueryTest() var tracks = Session.Query.All(); var result = from pd in from t in tracks - select new {ProductKey = t.Key, t.Name, TotalPrice = t.UnitPrice * t.UnitPrice} + select new { ProductKey = t.Key, t.Name, TotalPrice = t.UnitPrice * t.UnitPrice } where pd.TotalPrice > 100 - select new {PKey = pd.ProductKey, pd.Name, Total = pd.TotalPrice}; + select new { PKey = pd.ProductKey, pd.Name, Total = pd.TotalPrice }; var list = result.ToList(); } @@ -549,9 +557,9 @@ public void NestedQueryWithStructuresTest() from a in from id in from i in invoices - select new {ProductKey = i.Key, SupplierAddress = i.Customer.Address} - select new {PKey = id.ProductKey, id.SupplierAddress, SupplierCity = id.SupplierAddress.City} - select new {a.PKey, a.SupplierAddress, a.SupplierCity}; + select new { ProductKey = i.Key, SupplierAddress = i.Customer.Address } + select new { PKey = id.ProductKey, id.SupplierAddress, SupplierCity = id.SupplierAddress.City } + select new { a.PKey, a.SupplierAddress, a.SupplierCity }; var list = result.ToList(); } @@ -562,8 +570,8 @@ public void NestedQueryWithEntitiesTest() var tracks = Session.Query.All(); var result = from pd in from t in tracks - select new {ProductKey = t.Key, Product = t} - select new {PKey = pd.ProductKey, pd.Product}; + select new { ProductKey = t.Key, Product = t } + select new { PKey = pd.ProductKey, pd.Product }; var list = result.ToList(); } @@ -574,8 +582,8 @@ public void NestedQueryWithAnonymousTest() var tracks = Session.Query.All(); var result = from pd in from t in tracks - select new {ProductKey = t.Key, Product = new {Entity = new {t}, Name = t.Name}} - select new {PKey = pd.ProductKey, pd.Product.Name, A = pd, AProduct = pd.Product, AEntity = pd.Product.Entity}; + select new { ProductKey = t.Key, Product = new { Entity = new { t }, Name = t.Name } } + select new { PKey = pd.ProductKey, pd.Product.Name, A = pd, AProduct = pd.Product, AEntity = pd.Product.Entity }; var list = result.ToList(); } @@ -584,30 +592,32 @@ from t in tracks public void SelectEnumTest() { var result = from i in Session.Query.All() select i.InvoiceDate.DayOfWeek; - result.ToList(); + _ = result.ToList(); } [Test] public void SelectAnonymousEnumTest() { - var result = from i in Session.Query.All() select new {i.InvoiceDate.DayOfWeek}; - result.ToList(); + var result = from i in Session.Query.All() select new { i.InvoiceDate.DayOfWeek }; + _ = result.ToList(); } [Test] public void SelectEnumFieldTest() { var result = from t in Session.Query.All() select t.MediaFormat; - foreach (var t in result) + foreach (var t in result) { Assert.AreEqual(t, MediaFormat.Audio); + } } [Test] public void SelectAnonymousEnumFieldTest() { - var result = from t in Session.Query.All() select new {t.MediaFormat}; - foreach (var t in result) + var result = from t in Session.Query.All() select new { t.MediaFormat }; + foreach (var t in result) { Assert.AreEqual(t.MediaFormat, MediaFormat.Audio); + } } [Test] @@ -636,17 +646,19 @@ public void SelectEqualsTest() [Test] public void DoubleSelectEntitySet1Test() { - IQueryable> query = Session.Query.All().Select(c => c.Invoices).Select(c => c); - foreach (var order in query) + var query = Session.Query.All().Select(c => c.Invoices).Select(c => c); + foreach (var order in query) { QueryDumper.Dump(order); + } } [Test] public void DoubleSelectEntitySet2Test() { - IQueryable> query = Session.Query.All().Select(c => c).Select(c => c.Invoices); - foreach (var order in query) + var query = Session.Query.All().Select(c => c).Select(c => c.Invoices); + foreach (var order in query) { QueryDumper.Dump(order); + } } [Test] @@ -655,16 +667,17 @@ public void DoubleSelectEntitySet3Test() var query = Session.Query.All().Select(c => c.Invoices.Select(o => o)); // var query = Session.Query.All().Select(c => c.Orders); - foreach (var order in query) + foreach (var order in query) { QueryDumper.Dump(order); + } } [Test] public void NestedAnonymousTest() { var result = Session.Query.All() - .Select(c => new {c}) - .Select(a1 => new {a1}) + .Select(c => new { c }) + .Select(a1 => new { a1 }) .Select(a2 => a2.a1.c.CompanyName); QueryDumper.Dump(result); } @@ -672,8 +685,8 @@ public void NestedAnonymousTest() [Test] public void EntityWithLazyLoadFieldTest() { - var category = Session.Query.All().Where(c => c.Bytes!=null).First(); - int columnIndex = Domain.Model.Types[typeof (Track)].Fields["Bytes"].MappingInfo.Offset; + var category = Session.Query.All().Where(c => c.Bytes != null).First(); + var columnIndex = Domain.Model.Types[typeof(Track)].Fields["Bytes"].MappingInfo.Offset; Assert.IsFalse(category.State.Tuple.GetFieldState(columnIndex).IsAvailable()); } @@ -681,7 +694,7 @@ public void EntityWithLazyLoadFieldTest() public void AnonymousSelectTest() { var result = Session.Query.All() - .Select(i => new {i.InvoiceDate, i.Commission}) + .Select(i => new { i.InvoiceDate, i.Commission }) .Select(g => g.InvoiceDate); QueryDumper.Dump(result); } @@ -690,15 +703,16 @@ public void AnonymousSelectTest() public void SelectJustOuterParameterTest() { var result = Session.Query.All().Select(c => Session.Query.All().Select(s => c)); - foreach (var i in result) - i.ToList(); + foreach (var i in result) { + _ = i.ToList(); + } } [Test] public void NonPersistentFieldTest() { var result = from e in Session.Query.All() select e.FullName; - Assert.Throws(() => result.ToList()); + _ = Assert.Throws(() => result.ToList()); } [Test] @@ -707,7 +721,7 @@ public void SelectBigMulTest() var result = from invoice in Session.Query.All() select Math.BigMul(invoice.InvoiceId, invoice.DesignatedEmployee.EmployeeId); - result.ToList(); + _ = result.ToList(); } [Test] @@ -775,7 +789,7 @@ public void SelectStringIndexerTest() .OrderBy(item => item.String) .ToArray(); Assert.AreEqual(expected.Length, result.Length); - for (int i = 0; i < expected.Length; i++) { + for (var i = 0; i < expected.Length; i++) { Assert.AreEqual(expected[0].String, result[0].String); Assert.AreEqual(expected[0].Char0, result[0].Char0); Assert.AreEqual(expected[0].Char1, result[0].Char1); @@ -788,7 +802,7 @@ public void SelectStringIndexerTest() [Test] public void SelectIndexOfTest() { - char _char = 'A'; + var _char = 'A'; var result = Session.Query.All() .Select(c => new { @@ -818,7 +832,7 @@ public void SelectIndexOfTest() .OrderBy(item => item.String) .ToArray(); Assert.AreEqual(expected.Length, result.Length); - for (int i = 0; i < expected.Length; i++) { + for (var i = 0; i < expected.Length; i++) { Assert.AreEqual(expected[i].String, result[i].String); Assert.AreEqual(expected[i].IndexOfChar, result[i].IndexOfChar); Assert.AreEqual(expected[i].IndexOfCharStart, result[i].IndexOfCharStart); @@ -830,18 +844,37 @@ public void SelectIndexOfTest() } [Test] - public void SelectStringContainsTest() + public void SelectStringContainsTest1() + { + Require.ProviderIs(StorageProvider.Sqlite | StorageProvider.SqlServer | StorageProvider.MySql); + var result = + Session.Query.All() + .Where(c => c.FirstName.Contains('L')) + .OrderBy(c => c.CustomerId) + .ToArray(); + var expected = + Session.Query.All() + .ToList() + .Where(c => c.FirstName.Contains('L') || c.FirstName.Contains('l')) + .OrderBy(c => c.CustomerId) + .ToArray(); + Assert.IsTrue(expected.SequenceEqual(result)); + } + + [Test] + public void SelectStringContainsTest2() { + Require.ProviderIsNot(StorageProvider.Sqlite | StorageProvider.SqlServer | StorageProvider.MySql); var result = Session.Query.All() - .Where(c => c.FirstName.Contains('ç')) - .OrderBy(c => c.FirstName) + .Where(c => c.FirstName.Contains('L')) + .OrderBy(c => c.CustomerId) .ToArray(); var expected = Session.Query.All() .ToList() - .Where(c => c.FirstName.Contains('ç')) - .OrderBy(c => c.FirstName) + .Where(c => c.FirstName.Contains('L')) + .OrderBy(c => c.CustomerId) .ToArray(); Assert.IsTrue(expected.SequenceEqual(result)); } @@ -938,7 +971,7 @@ public void ExternalPropertyCall() { Require.AllFeaturesSupported(ProviderFeatures.TemporaryTables); Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); - var query = Session.Query.All().Select(c => Customers.Single(c2 => c2==c)).ToList(); + var query = Session.Query.All().Select(c => Customers.Single(c2 => c2 == c)).ToList(); } [Test] @@ -946,10 +979,10 @@ public void ExternalMethodCall() { Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() - .Select(c => GetCustomers().Single(c2 => c2==c)); + .Select(c => GetCustomers().Single(c2 => c2 == c)); var expected = Session.Query.All() .AsEnumerable() - .Select(c => GetCustomers().AsEnumerable().Single(c2 => c2==c)); + .Select(c => GetCustomers().AsEnumerable().Single(c2 => c2 == c)); Assert.AreEqual(0, expected.Except(query).Count()); } @@ -958,10 +991,10 @@ public void ExternalMethodWithCorrectParams1Call() { Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() - .Select(c => GetCustomers(1).Single(c2 => c2==c)); + .Select(c => GetCustomers(1).Single(c2 => c2 == c)); var expected = Session.Query.All() .AsEnumerable() - .Select(c => GetCustomers(1).AsEnumerable().Single(c2 => c2==c)); + .Select(c => GetCustomers(1).AsEnumerable().Single(c2 => c2 == c)); Assert.AreEqual(0, expected.Except(query).Count()); } @@ -969,20 +1002,20 @@ public void ExternalMethodWithCorrectParams1Call() public void ExternalMethodWithCorrectParams2Call() { Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); - int count = 1; + var count = 1; var query = Session.Query.All() - .Select(c => GetCustomers(count).Single(c2 => c2==c)); + .Select(c => GetCustomers(count).Single(c2 => c2 == c)); var expected = Session.Query.All() .AsEnumerable() - .Select(c => GetCustomers(count).AsEnumerable().Single(c2 => c2==c)); + .Select(c => GetCustomers(count).AsEnumerable().Single(c2 => c2 == c)); Assert.AreEqual(0, expected.Except(query).Count()); } [Test] public void ExternalMethodWithIncorrectParamsCall() { - Assert.Throws(() => { - var query = Session.Query.All().Select(c => GetCustomers(c.Invoices.Count()).Single(c2 => c2==c)).ToList(); + _ = Assert.Throws(() => { + var query = Session.Query.All().Select(c => GetCustomers(c.Invoices.Count()).Single(c2 => c2 == c)).ToList(); }); } diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Chinook.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Chinook.cs index fca3c2d426..4653172bb7 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Chinook.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Chinook.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2019-2021 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 Kudelin // Created: 2019.09.19 @@ -17,6 +17,7 @@ public interface IHasCommission : IEntity decimal? Commission { get; set; } } + [Index("Title")] [HierarchyRoot] [DebuggerDisplay("{Title} (AlbumId = {AlbumId})")] public class Album : Entity @@ -51,10 +52,7 @@ public abstract class Person : Entity [Field(Nullable = false, Length = 20)] public string FirstName { get; set; } - public string FullName - { - get { return FirstName + " " + LastName; } - } + public string FullName => FirstName + " " + LastName; [Field] public Address Address { get; set; } @@ -75,6 +73,7 @@ public abstract class BusinessContact : Person public string CompanyName { get; set; } } + [Index("FirstName")] [HierarchyRoot] [DebuggerDisplay("{FirstName} {LastName} (CustomerId = {CustomerId})")] public class Customer : BusinessContact @@ -216,6 +215,8 @@ public class Playlist : Entity public EntitySet Tracks { get; private set; } } + [Index("Composer")] + [Index("Milliseconds")] [HierarchyRoot(InheritanceSchema.SingleTable)] [DebuggerDisplay("{Name} (TrackId = {TrackId})")] public abstract class Track : Entity From d4064aa64d89967c08cdb2cb0387c9e0b031b021 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 20:42:07 +0500 Subject: [PATCH 05/71] Fix DateTime connected tests Tests were corrected due to the fact that some RDBMSs are unable to store full .Net DateTime (Mysql does not store milliseconds at all) --- .../TestHelper.cs | 45 ++++- .../Issues/Issue0717_VersionCheckBug.cs | 15 +- .../Issues/IssueJira0421_DateTimeAddXxx.cs | 32 ++-- ...ueJira0593_AggregateForSingleColumnTest.cs | 30 ++-- .../DateTime/ComparisonTest.cs | 24 ++- .../DateTime/OperationsTest.cs | 156 +++++++++--------- .../DateTime/PartsExtractionTest.cs | 142 ++++++++-------- .../DateTime/WhereTest.cs | 27 +-- 8 files changed, 278 insertions(+), 193 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs b/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs index a5a72b6f61..deaa2082f2 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.02.09 @@ -28,11 +28,12 @@ public static void CollectGarbage() /// Full rather then fast collection should be performed. public static void CollectGarbage(bool preferFullRatherThanFast) { - int baseSleepTime = 1; - if (preferFullRatherThanFast) + var baseSleepTime = 1; + if (preferFullRatherThanFast) { baseSleepTime = 100; + } - for (int i = 0; i<5; i++) { + for (var i = 0; i<5; i++) { Thread.Sleep(baseSleepTime); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); @@ -48,5 +49,37 @@ public static System.Configuration.Configuration GetConfigurationForAssembly(thi { return instanceOfTypeFromAssembly.GetType().Assembly.GetAssemblyConfiguration(); } + + /// + /// Cuts down resolution of value if needed. + /// + /// The value to fix. + /// Type of provider. + /// New value with less resolution if requires it or untouched if the provider doesn't + public static DateTime FixDateTimeForProvider(this DateTime origin, StorageProvider provider) + { + long? divider; + switch (provider) { + case StorageProvider.MySql: + divider = 10000000; + break; + case StorageProvider.Firebird: + divider = 1000; + break; + case StorageProvider.PostgreSql: + divider = 10; + break; + default: + divider = null; + break; + } + + if (!divider.HasValue) { + return origin; + } + var ticks = origin.Ticks; + var newTicks = ticks - (ticks % divider.Value); + return new DateTime(newTicks); + } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs index d05a1106ee..9725fe9e07 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2010-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2010.06.24 @@ -40,6 +40,15 @@ public class Issue0717_VersionCheckBug : AutoBuildTest { private const string VersionFieldName = "Version"; + protected override void CheckRequirements() + { + base.CheckRequirements(); + // MySQL does not store milliseconds + // and we increase Millisecond part of DateTime value on Version increase + // so test is irrelevant to this RDBMS + Require.ProviderIsNot(StorageProvider.MySql); + } + protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0421_DateTimeAddXxx.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0421_DateTimeAddXxx.cs index 56d4a98990..fcfe848da6 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0421_DateTimeAddXxx.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0421_DateTimeAddXxx.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 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 // Created: 2013.02.14 @@ -31,6 +31,7 @@ public class IssueJira0421_DateTimeAddXxx : AutoBuildTest { // private DateTime today = new DateTime(2016, 01, 02, 03, 04, 05, 347); todo This Value failed with sqlite provider because of accuracy millisecond error private DateTime today = new DateTime(2016, 01, 02, 03, 04, 05, 348); + protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); @@ -69,7 +70,7 @@ private void RunAllTestsDouble(Func> filter) + private static void RunTest(Session session, Expression> filter) { var count = session.Query.All().Count(filter); Assert.That(count, Is.EqualTo(1)); @@ -78,43 +79,52 @@ private static void RunTest(Session session, Expression e => e.Today.AddYears(value)==today.AddYears(value)); + RunAllTestsInt(value => e => e.Today.AddYears(value) == today.AddYears(value)); } [Test] public void AddMonthsTest() { - RunAllTestsInt(value => e => e.Today.AddMonths(value)==today.AddMonths(value)); + RunAllTestsInt(value => e => e.Today.AddMonths(value) == today.AddMonths(value)); } [Test] public void AddDaysTest() { - RunAllTestsDouble(value => e => e.Today.AddDays(value)==today.AddDays(value)); + RunAllTestsDouble(value => e => e.Today.AddDays(value) == today.AddDays(value)); } [Test] public void AddHoursTest() { - RunAllTestsDouble(value => e => e.Today.AddHours(value)==today.AddHours(value)); + RunAllTestsDouble(value => e => e.Today.AddHours(value) == today.AddHours(value)); } [Test] public void AddMinutesTest() { - RunAllTestsDouble(value => e => e.Today.AddMinutes(value)==today.AddMinutes(value)); + RunAllTestsDouble(value => e => e.Today.AddMinutes(value) == today.AddMinutes(value)); } [Test] public void AddSecondsTest() { - RunAllTestsDouble(value => e => e.Today.AddSeconds(value)==today.AddSeconds(value)); + RunAllTestsDouble(value => e => e.Today.AddSeconds(value) == today.AddSeconds(value)); } [Test] public void AddMillisecondsTest() { - RunAllTestsDouble(value => e => e.Today.AddMilliseconds(value)==today.AddMilliseconds(value)); + CheckNotMySql55(); + RunAllTestsDouble(value => e => e.Today.AddMilliseconds(value) == today.AddMilliseconds(value)); + } + + private void CheckNotMySql55() + { + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.MySql) + && StorageProviderInfo.Instance.CheckProviderVersionIsAtMost(StorageProviderVersion.MySql56)) { + throw new IgnoreException("Test requires MySQL version greater than 5.5"); + } } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs index 6bcae90608..769587ad30 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Groznov // Created: 2016.09.02 @@ -675,10 +675,10 @@ private static void CheckQueryable(IQueryable query) private static void CheckQueryable(IQueryable query) { var localArray = query.ToArray(); - Assert.AreEqual(localArray.Min(), query.Min(c => c)); - Assert.AreEqual(localArray.Min(), query.Min()); - Assert.AreEqual(localArray.Max(), query.Max(c => c)); - Assert.AreEqual(localArray.Max(), query.Max()); + Assert.AreEqual(localArray.Min().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Min(c => c)); + Assert.AreEqual(localArray.Min().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Min()); + Assert.AreEqual(localArray.Max().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Max(c => c)); + Assert.AreEqual(localArray.Max().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Max()); Assert.AreEqual(localArray.Count(), query.Count()); } @@ -695,20 +695,20 @@ private static void CheckQueryable(IQueryable query) private static void CheckQueryable(IQueryable query) { var localArray = query.ToArray(); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min(c => c))); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min())); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max(c => c))); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max())); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min(c => c))); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min())); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max(c => c))); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max())); Assert.AreEqual(localArray.Count(), query.Count()); } private static void CheckQueryable(IQueryable query) { var localArray = query.ToArray(); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min(c => c))); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min())); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max(c => c))); - Assert.Throws(typeof (QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max())); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min(c => c))); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Min())); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max(c => c))); + _ = Assert.Throws(typeof(QueryTranslationException), () => Assert.AreEqual(localArray.Min(), query.Max())); Assert.AreEqual(localArray.Count(), query.Count()); } diff --git a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/ComparisonTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/ComparisonTest.cs index 9534473936..e0dd74a9fb 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/ComparisonTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/ComparisonTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Groznov // Created: 2016.08.01 @@ -39,6 +39,7 @@ public void NotEqualTest() [Test] public void CompareTest() { + Require.ProviderIsNot(StorageProvider.MySql); ExecuteInsideSession(() => { RunTest(c => c.DateTime > FirstDateTime.Date); RunTest(c => c.DateTime > FirstDateTime.AddSeconds(-1)); @@ -53,5 +54,22 @@ public void CompareTest() RunWrongTest(c => c.MillisecondDateTime < FirstMillisecondDateTime.Date); }); } + + [Test] + public void MysqlCompareTest() + { + Require.ProviderIs(StorageProvider.MySql); + ExecuteInsideSession(() => { + RunTest(c => c.DateTime > FirstDateTime.Date); + RunTest(c => c.DateTime > FirstDateTime.AddSeconds(-1)); + + RunTest(c => c.DateTime < FirstDateTime.Date.AddDays(1)); + RunTest(c => c.DateTime < FirstDateTime.AddSeconds(1)); + + RunWrongTest(c => c.DateTime > FirstDateTime); + RunWrongTest(c => c.MillisecondDateTime > FirstMillisecondDateTime); + RunWrongTest(c => c.MillisecondDateTime < FirstMillisecondDateTime.Date); + }); + } } } diff --git a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs index 2629b5b40d..2c7197404d 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Groznov // Created: 2016.08.01 @@ -15,13 +15,13 @@ public class OperationsTest : DateTimeBaseTest public void AddYearsTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.AddYears(1)==FirstDateTime.AddYears(1)); - RunTest(c => c.MillisecondDateTime.AddYears(-2)==FirstMillisecondDateTime.AddYears(-2)); - RunTest(c => c.NullableDateTime.Value.AddYears(33)==NullableDateTime.AddYears(33)); + RunTest(c => c.DateTime.AddYears(1) == FirstDateTime.AddYears(1)); + RunTest(c => c.MillisecondDateTime.AddYears(-2) == FirstMillisecondDateTime.AddYears(-2)); + RunTest(c => c.NullableDateTime.Value.AddYears(33) == NullableDateTime.AddYears(33)); - RunWrongTest(c => c.DateTime.AddYears(1)==FirstDateTime.AddYears(2)); - RunWrongTest(c => c.MillisecondDateTime.AddYears(-1)==FirstMillisecondDateTime.AddYears(-2)); - RunWrongTest(c => c.NullableDateTime.Value.AddYears(33)==NullableDateTime.AddYears(44)); + RunWrongTest(c => c.DateTime.AddYears(1) == FirstDateTime.AddYears(2)); + RunWrongTest(c => c.MillisecondDateTime.AddYears(-1) == FirstMillisecondDateTime.AddYears(-2)); + RunWrongTest(c => c.NullableDateTime.Value.AddYears(33) == NullableDateTime.AddYears(44)); }); } @@ -29,13 +29,13 @@ public void AddYearsTest() public void AddMonthsTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.AddMonths(1)==FirstDateTime.AddMonths(1)); - RunTest(c => c.MillisecondDateTime.AddMonths(-2)==FirstMillisecondDateTime.AddMonths(-2)); - RunTest(c => c.NullableDateTime.Value.AddMonths(33)==NullableDateTime.AddMonths(33)); + RunTest(c => c.DateTime.AddMonths(1) == FirstDateTime.AddMonths(1)); + RunTest(c => c.MillisecondDateTime.AddMonths(-2) == FirstMillisecondDateTime.AddMonths(-2)); + RunTest(c => c.NullableDateTime.Value.AddMonths(33) == NullableDateTime.AddMonths(33)); - RunWrongTest(c => c.DateTime.AddMonths(1)==FirstDateTime.AddMonths(2)); - RunWrongTest(c => c.MillisecondDateTime.AddMonths(-1)==FirstMillisecondDateTime.AddMonths(-2)); - RunWrongTest(c => c.NullableDateTime.Value.AddMonths(33)==NullableDateTime.AddMonths(44)); + RunWrongTest(c => c.DateTime.AddMonths(1) == FirstDateTime.AddMonths(2)); + RunWrongTest(c => c.MillisecondDateTime.AddMonths(-1) == FirstMillisecondDateTime.AddMonths(-2)); + RunWrongTest(c => c.NullableDateTime.Value.AddMonths(33) == NullableDateTime.AddMonths(44)); }); } @@ -43,13 +43,13 @@ public void AddMonthsTest() public void AddDaysTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.AddDays(1)==FirstDateTime.AddDays(1)); - RunTest(c => c.MillisecondDateTime.AddDays(-2)==FirstMillisecondDateTime.AddDays(-2)); - RunTest(c => c.NullableDateTime.Value.AddDays(33)==NullableDateTime.AddDays(33)); + RunTest(c => c.DateTime.AddDays(1) == FirstDateTime.AddDays(1)); + RunTest(c => c.MillisecondDateTime.AddDays(-2) == FirstMillisecondDateTime.AddDays(-2)); + RunTest(c => c.NullableDateTime.Value.AddDays(33) == NullableDateTime.AddDays(33)); - RunWrongTest(c => c.DateTime.AddDays(1)==FirstDateTime.AddDays(2)); - RunWrongTest(c => c.MillisecondDateTime.AddDays(-1)==FirstMillisecondDateTime.AddDays(-2)); - RunWrongTest(c => c.NullableDateTime.Value.AddDays(33)==NullableDateTime.AddDays(44)); + RunWrongTest(c => c.DateTime.AddDays(1) == FirstDateTime.AddDays(2)); + RunWrongTest(c => c.MillisecondDateTime.AddDays(-1) == FirstMillisecondDateTime.AddDays(-2)); + RunWrongTest(c => c.NullableDateTime.Value.AddDays(33) == NullableDateTime.AddDays(44)); }); } @@ -57,13 +57,13 @@ public void AddDaysTest() public void AddHoursTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.AddHours(1)==FirstDateTime.AddHours(1)); - RunTest(c => c.MillisecondDateTime.AddHours(-2)==FirstMillisecondDateTime.AddHours(-2)); - RunTest(c => c.NullableDateTime.Value.AddHours(33)==NullableDateTime.AddHours(33)); + RunTest(c => c.DateTime.AddHours(1) == FirstDateTime.AddHours(1)); + RunTest(c => c.MillisecondDateTime.AddHours(-2) == FirstMillisecondDateTime.AddHours(-2)); + RunTest(c => c.NullableDateTime.Value.AddHours(33) == NullableDateTime.AddHours(33)); - RunWrongTest(c => c.DateTime.AddHours(1)==FirstDateTime.AddHours(2)); - RunWrongTest(c => c.MillisecondDateTime.AddHours(-1)==FirstMillisecondDateTime.AddHours(-2)); - RunWrongTest(c => c.NullableDateTime.Value.AddHours(33)==NullableDateTime.AddHours(44)); + RunWrongTest(c => c.DateTime.AddHours(1) == FirstDateTime.AddHours(2)); + RunWrongTest(c => c.MillisecondDateTime.AddHours(-1) == FirstMillisecondDateTime.AddHours(-2)); + RunWrongTest(c => c.NullableDateTime.Value.AddHours(33) == NullableDateTime.AddHours(44)); }); } @@ -71,13 +71,13 @@ public void AddHoursTest() public void AddMinutesTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.AddMinutes(1)==FirstDateTime.AddMinutes(1)); - RunTest(c => c.MillisecondDateTime.AddMinutes(-2)==FirstMillisecondDateTime.AddMinutes(-2)); - RunTest(c => c.NullableDateTime.Value.AddMinutes(33)==NullableDateTime.AddMinutes(33)); + RunTest(c => c.DateTime.AddMinutes(1) == FirstDateTime.AddMinutes(1)); + RunTest(c => c.MillisecondDateTime.AddMinutes(-2) == FirstMillisecondDateTime.AddMinutes(-2)); + RunTest(c => c.NullableDateTime.Value.AddMinutes(33) == NullableDateTime.AddMinutes(33)); - RunWrongTest(c => c.DateTime.AddMinutes(1)==FirstDateTime.AddMinutes(2)); - RunWrongTest(c => c.MillisecondDateTime.AddMinutes(-1)==FirstMillisecondDateTime.AddMinutes(-2)); - RunWrongTest(c => c.NullableDateTime.Value.AddMinutes(33)==NullableDateTime.AddMinutes(44)); + RunWrongTest(c => c.DateTime.AddMinutes(1) == FirstDateTime.AddMinutes(2)); + RunWrongTest(c => c.MillisecondDateTime.AddMinutes(-1) == FirstMillisecondDateTime.AddMinutes(-2)); + RunWrongTest(c => c.NullableDateTime.Value.AddMinutes(33) == NullableDateTime.AddMinutes(44)); }); } @@ -85,22 +85,23 @@ public void AddMinutesTest() public void AddSecondsTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.AddSeconds(1)==FirstDateTime.AddSeconds(1)); - RunTest(c => c.MillisecondDateTime.AddSeconds(-2)==FirstMillisecondDateTime.AddSeconds(-2)); - RunTest(c => c.NullableDateTime.Value.AddSeconds(33)==NullableDateTime.AddSeconds(33)); + RunTest(c => c.DateTime.AddSeconds(1) == FirstDateTime.AddSeconds(1)); + RunTest(c => c.MillisecondDateTime.AddSeconds(-2) == FirstMillisecondDateTime.AddSeconds(-2)); + RunTest(c => c.NullableDateTime.Value.AddSeconds(33) == NullableDateTime.AddSeconds(33)); - RunWrongTest(c => c.DateTime.AddSeconds(1)==FirstDateTime.AddSeconds(2)); - RunWrongTest(c => c.MillisecondDateTime.AddSeconds(-1)==FirstMillisecondDateTime.AddSeconds(-2)); - RunWrongTest(c => c.NullableDateTime.Value.AddSeconds(33)==NullableDateTime.AddSeconds(44)); + RunWrongTest(c => c.DateTime.AddSeconds(1) == FirstDateTime.AddSeconds(2)); + RunWrongTest(c => c.MillisecondDateTime.AddSeconds(-1) == FirstMillisecondDateTime.AddSeconds(-2)); + RunWrongTest(c => c.NullableDateTime.Value.AddSeconds(33) == NullableDateTime.AddSeconds(44)); }); } [Test] public void AddMillisecondsTest() { + Require.ProviderIsNot(StorageProvider.MySql); ExecuteInsideSession(() => { - RunTest(c => c.MillisecondDateTime.AddMilliseconds(-2)==FirstMillisecondDateTime.AddMilliseconds(-2)); - RunWrongTest(c => c.MillisecondDateTime.AddMilliseconds(-1)==FirstMillisecondDateTime.AddMilliseconds(-2)); + RunTest(c => c.MillisecondDateTime.AddMilliseconds(-2) == FirstMillisecondDateTime.AddMilliseconds(-2)); + RunWrongTest(c => c.MillisecondDateTime.AddMilliseconds(-1) == FirstMillisecondDateTime.AddMilliseconds(-2)); }); } @@ -108,13 +109,13 @@ public void AddMillisecondsTest() public void AddTimeSpanTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Add(FirstOffset)==FirstDateTime.Add(FirstOffset)); - RunTest(c => c.MillisecondDateTime.Add(SecondOffset)==FirstMillisecondDateTime.Add(SecondOffset)); - RunTest(c => c.NullableDateTime.Value.Add(FirstOffset)==NullableDateTime.Add(FirstOffset)); + RunTest(c => c.DateTime.Add(FirstOffset) == FirstDateTime.Add(FirstOffset)); + RunTest(c => c.MillisecondDateTime.Add(SecondOffset) == FirstMillisecondDateTime.Add(SecondOffset)); + RunTest(c => c.NullableDateTime.Value.Add(FirstOffset) == NullableDateTime.Add(FirstOffset)); - RunWrongTest(c => c.DateTime.Add(FirstOffset)==FirstDateTime.Add(WrongOffset)); - RunWrongTest(c => c.MillisecondDateTime.Add(SecondOffset)==FirstMillisecondDateTime.Add(WrongOffset)); - RunWrongTest(c => c.NullableDateTime.Value.Add(FirstOffset)==NullableDateTime.Add(WrongOffset)); + RunWrongTest(c => c.DateTime.Add(FirstOffset) == FirstDateTime.Add(WrongOffset)); + RunWrongTest(c => c.MillisecondDateTime.Add(SecondOffset) == FirstMillisecondDateTime.Add(WrongOffset)); + RunWrongTest(c => c.NullableDateTime.Value.Add(FirstOffset) == NullableDateTime.Add(WrongOffset)); }); } @@ -122,27 +123,28 @@ public void AddTimeSpanTest() public void SubtractTimeSpanTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Subtract(FirstOffset)==FirstDateTime.Subtract(FirstOffset)); - RunTest(c => c.MillisecondDateTime.Subtract(SecondOffset)==FirstMillisecondDateTime.Subtract(SecondOffset)); - RunTest(c => c.NullableDateTime.Value.Subtract(FirstOffset)==NullableDateTime.Subtract(FirstOffset)); + RunTest(c => c.DateTime.Subtract(FirstOffset) == FirstDateTime.Subtract(FirstOffset)); + RunTest(c => c.MillisecondDateTime.Subtract(SecondOffset) == FirstMillisecondDateTime.Subtract(SecondOffset)); + RunTest(c => c.NullableDateTime.Value.Subtract(FirstOffset) == NullableDateTime.Subtract(FirstOffset)); - RunWrongTest(c => c.DateTime.Subtract(FirstOffset)==FirstDateTime.Subtract(WrongOffset)); - RunWrongTest(c => c.MillisecondDateTime.Subtract(SecondOffset)==FirstMillisecondDateTime.Subtract(WrongOffset)); - RunWrongTest(c => c.NullableDateTime.Value.Subtract(FirstOffset)==NullableDateTime.Subtract(WrongOffset)); + RunWrongTest(c => c.DateTime.Subtract(FirstOffset) == FirstDateTime.Subtract(WrongOffset)); + RunWrongTest(c => c.MillisecondDateTime.Subtract(SecondOffset) == FirstMillisecondDateTime.Subtract(WrongOffset)); + RunWrongTest(c => c.NullableDateTime.Value.Subtract(FirstOffset) == NullableDateTime.Subtract(WrongOffset)); }); } [Test] public void SubtractDateTimeTest() { + Require.ProviderIsNot(StorageProvider.MySql); ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Subtract(SecondDateTime)==FirstDateTime.Subtract(SecondDateTime)); - RunTest(c => c.MillisecondDateTime.Subtract(SecondDateTime)==FirstMillisecondDateTime.Subtract(SecondDateTime)); - RunTest(c => c.NullableDateTime.Value.Subtract(SecondDateTime)==NullableDateTime.Subtract(SecondDateTime)); + RunTest(c => c.DateTime.Subtract(SecondDateTime) == FirstDateTime.Subtract(SecondDateTime)); + RunTest(c => c.MillisecondDateTime.Subtract(SecondDateTime) == FirstMillisecondDateTime.Subtract(SecondDateTime)); + RunTest(c => c.NullableDateTime.Value.Subtract(SecondDateTime) == NullableDateTime.Subtract(SecondDateTime)); - RunWrongTest(c => c.DateTime.Subtract(SecondDateTime)==FirstDateTime.Subtract(WrongDateTime)); - RunWrongTest(c => c.MillisecondDateTime.Subtract(SecondDateTime)==FirstMillisecondDateTime.Subtract(WrongDateTime)); - RunWrongTest(c => c.NullableDateTime.Value.Subtract(SecondDateTime)==NullableDateTime.Subtract(WrongDateTime)); + RunWrongTest(c => c.DateTime.Subtract(SecondDateTime) == FirstDateTime.Subtract(WrongDateTime)); + RunWrongTest(c => c.MillisecondDateTime.Subtract(SecondDateTime) == FirstMillisecondDateTime.Subtract(WrongDateTime)); + RunWrongTest(c => c.NullableDateTime.Value.Subtract(SecondDateTime) == NullableDateTime.Subtract(WrongDateTime)); }); } @@ -150,13 +152,13 @@ public void SubtractDateTimeTest() public void PlusTimeSpanTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime + FirstOffset==FirstDateTime + FirstOffset); - RunTest(c => c.MillisecondDateTime + SecondOffset==FirstMillisecondDateTime + SecondOffset); - RunTest(c => c.NullableDateTime + FirstOffset==NullableDateTime + FirstOffset); + RunTest(c => c.DateTime + FirstOffset == FirstDateTime + FirstOffset); + RunTest(c => c.MillisecondDateTime + SecondOffset == FirstMillisecondDateTime + SecondOffset); + RunTest(c => c.NullableDateTime + FirstOffset == NullableDateTime + FirstOffset); - RunWrongTest(c => c.DateTime + FirstOffset==FirstDateTime + WrongOffset); - RunWrongTest(c => c.MillisecondDateTime + SecondOffset==FirstMillisecondDateTime + WrongOffset); - RunWrongTest(c => c.NullableDateTime + FirstOffset==NullableDateTime + WrongOffset); + RunWrongTest(c => c.DateTime + FirstOffset == FirstDateTime + WrongOffset); + RunWrongTest(c => c.MillisecondDateTime + SecondOffset == FirstMillisecondDateTime + WrongOffset); + RunWrongTest(c => c.NullableDateTime + FirstOffset == NullableDateTime + WrongOffset); }); } @@ -164,13 +166,13 @@ public void PlusTimeSpanTest() public void MinusTimeSpanTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime - FirstOffset==FirstDateTime - FirstOffset); - RunTest(c => c.MillisecondDateTime - SecondOffset==FirstMillisecondDateTime - SecondOffset); - RunTest(c => c.NullableDateTime - FirstOffset==NullableDateTime - FirstOffset); + RunTest(c => c.DateTime - FirstOffset == FirstDateTime - FirstOffset); + RunTest(c => c.MillisecondDateTime - SecondOffset == FirstMillisecondDateTime - SecondOffset); + RunTest(c => c.NullableDateTime - FirstOffset == NullableDateTime - FirstOffset); - RunWrongTest(c => c.DateTime - FirstOffset==FirstDateTime - WrongOffset); - RunWrongTest(c => c.MillisecondDateTime - SecondOffset==FirstMillisecondDateTime - WrongOffset); - RunWrongTest(c => c.NullableDateTime - FirstOffset==NullableDateTime - WrongOffset); + RunWrongTest(c => c.DateTime - FirstOffset == FirstDateTime - WrongOffset); + RunWrongTest(c => c.MillisecondDateTime - SecondOffset == FirstMillisecondDateTime - WrongOffset); + RunWrongTest(c => c.NullableDateTime - FirstOffset == NullableDateTime - WrongOffset); }); } @@ -178,13 +180,13 @@ public void MinusTimeSpanTest() public void MinusDateTimeTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime - SecondDateTime==FirstDateTime - SecondDateTime); - RunTest(c => c.MillisecondDateTime - SecondDateTime==FirstMillisecondDateTime - SecondDateTime); - RunTest(c => c.NullableDateTime - SecondDateTime==NullableDateTime - SecondDateTime); + RunTest(c => c.DateTime - SecondDateTime == FirstDateTime - SecondDateTime); + RunTest(c => c.MillisecondDateTime - SecondDateTime == FirstMillisecondDateTime - SecondDateTime); + RunTest(c => c.NullableDateTime - SecondDateTime == NullableDateTime - SecondDateTime); - RunWrongTest(c => c.DateTime - SecondDateTime==FirstDateTime - WrongDateTime); - RunWrongTest(c => c.MillisecondDateTime - SecondDateTime==FirstMillisecondDateTime - WrongDateTime); - RunWrongTest(c => c.NullableDateTime - SecondDateTime==NullableDateTime - WrongDateTime); + RunWrongTest(c => c.DateTime - SecondDateTime == FirstDateTime - WrongDateTime); + RunWrongTest(c => c.MillisecondDateTime - SecondDateTime == FirstMillisecondDateTime - WrongDateTime); + RunWrongTest(c => c.NullableDateTime - SecondDateTime == NullableDateTime - WrongDateTime); }); } } diff --git a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs index bc061416f4..790f7c272c 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Groznov // Created: 2016.08.01 @@ -15,13 +15,13 @@ public class PartsExtractionTest : DateTimeBaseTest public void ExtractYearTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Year==FirstDateTime.Year); - RunTest(c => c.MillisecondDateTime.Year==FirstMillisecondDateTime.Year); - RunTest(c => c.NullableDateTime.Value.Year==NullableDateTime.Year); + RunTest(c => c.DateTime.Year == FirstDateTime.Year); + RunTest(c => c.MillisecondDateTime.Year == FirstMillisecondDateTime.Year); + RunTest(c => c.NullableDateTime.Value.Year == NullableDateTime.Year); - RunWrongTest(c => c.DateTime.Year==WrongDateTime.Year); - RunWrongTest(c => c.MillisecondDateTime.Year==WrongMillisecondDateTime.Year); - RunWrongTest(c => c.NullableDateTime.Value.Year==WrongDateTime.Year); + RunWrongTest(c => c.DateTime.Year == WrongDateTime.Year); + RunWrongTest(c => c.MillisecondDateTime.Year == WrongMillisecondDateTime.Year); + RunWrongTest(c => c.NullableDateTime.Value.Year == WrongDateTime.Year); }); } @@ -29,13 +29,13 @@ public void ExtractYearTest() public void ExtractMonthTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Month==FirstDateTime.Month); - RunTest(c => c.MillisecondDateTime.Month==FirstMillisecondDateTime.Month); - RunTest(c => c.NullableDateTime.Value.Month==NullableDateTime.Month); + RunTest(c => c.DateTime.Month == FirstDateTime.Month); + RunTest(c => c.MillisecondDateTime.Month == FirstMillisecondDateTime.Month); + RunTest(c => c.NullableDateTime.Value.Month == NullableDateTime.Month); - RunWrongTest(c => c.DateTime.Month==WrongDateTime.Month); - RunWrongTest(c => c.MillisecondDateTime.Month==WrongMillisecondDateTime.Month); - RunWrongTest(c => c.NullableDateTime.Value.Month==WrongDateTime.Month); + RunWrongTest(c => c.DateTime.Month == WrongDateTime.Month); + RunWrongTest(c => c.MillisecondDateTime.Month == WrongMillisecondDateTime.Month); + RunWrongTest(c => c.NullableDateTime.Value.Month == WrongDateTime.Month); }); } @@ -43,13 +43,13 @@ public void ExtractMonthTest() public void ExtractDayTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Day==FirstDateTime.Day); - RunTest(c => c.MillisecondDateTime.Day==FirstMillisecondDateTime.Day); - RunTest(c => c.NullableDateTime.Value.Day==NullableDateTime.Day); + RunTest(c => c.DateTime.Day == FirstDateTime.Day); + RunTest(c => c.MillisecondDateTime.Day == FirstMillisecondDateTime.Day); + RunTest(c => c.NullableDateTime.Value.Day == NullableDateTime.Day); - RunWrongTest(c => c.DateTime.Day==WrongDateTime.Day); - RunWrongTest(c => c.MillisecondDateTime.Day==WrongMillisecondDateTime.Day); - RunWrongTest(c => c.NullableDateTime.Value.Day==WrongDateTime.Day); + RunWrongTest(c => c.DateTime.Day == WrongDateTime.Day); + RunWrongTest(c => c.MillisecondDateTime.Day == WrongMillisecondDateTime.Day); + RunWrongTest(c => c.NullableDateTime.Value.Day == WrongDateTime.Day); }); } @@ -57,13 +57,13 @@ public void ExtractDayTest() public void ExtractHourTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Hour==FirstDateTime.Hour); - RunTest(c => c.MillisecondDateTime.Hour==FirstMillisecondDateTime.Hour); - RunTest(c => c.NullableDateTime.Value.Hour==NullableDateTime.Hour); + RunTest(c => c.DateTime.Hour == FirstDateTime.Hour); + RunTest(c => c.MillisecondDateTime.Hour == FirstMillisecondDateTime.Hour); + RunTest(c => c.NullableDateTime.Value.Hour == NullableDateTime.Hour); - RunWrongTest(c => c.DateTime.Hour==WrongDateTime.Hour); - RunWrongTest(c => c.MillisecondDateTime.Hour==WrongMillisecondDateTime.Hour); - RunWrongTest(c => c.NullableDateTime.Value.Hour==WrongDateTime.Hour); + RunWrongTest(c => c.DateTime.Hour == WrongDateTime.Hour); + RunWrongTest(c => c.MillisecondDateTime.Hour == WrongMillisecondDateTime.Hour); + RunWrongTest(c => c.NullableDateTime.Value.Hour == WrongDateTime.Hour); }); } @@ -71,13 +71,13 @@ public void ExtractHourTest() public void ExtractMinuteTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Minute==FirstDateTime.Minute); - RunTest(c => c.MillisecondDateTime.Minute==FirstMillisecondDateTime.Minute); - RunTest(c => c.NullableDateTime.Value.Minute==NullableDateTime.Minute); + RunTest(c => c.DateTime.Minute == FirstDateTime.Minute); + RunTest(c => c.MillisecondDateTime.Minute == FirstMillisecondDateTime.Minute); + RunTest(c => c.NullableDateTime.Value.Minute == NullableDateTime.Minute); - RunWrongTest(c => c.DateTime.Minute==WrongDateTime.Minute); - RunWrongTest(c => c.MillisecondDateTime.Minute==WrongMillisecondDateTime.Minute); - RunWrongTest(c => c.NullableDateTime.Value.Minute==WrongDateTime.Minute); + RunWrongTest(c => c.DateTime.Minute == WrongDateTime.Minute); + RunWrongTest(c => c.MillisecondDateTime.Minute == WrongMillisecondDateTime.Minute); + RunWrongTest(c => c.NullableDateTime.Value.Minute == WrongDateTime.Minute); }); } @@ -85,22 +85,34 @@ public void ExtractMinuteTest() public void ExtractSecondTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Second==FirstDateTime.Second); - RunTest(c => c.MillisecondDateTime.Second==FirstMillisecondDateTime.Second); - RunTest(c => c.NullableDateTime.Value.Second==NullableDateTime.Second); + RunTest(c => c.DateTime.Second == FirstDateTime.Second); + RunTest(c => c.MillisecondDateTime.Second == FirstMillisecondDateTime.Second); + RunTest(c => c.NullableDateTime.Value.Second == NullableDateTime.Second); - RunWrongTest(c => c.DateTime.Second==WrongDateTime.Second); - RunWrongTest(c => c.MillisecondDateTime.Second==WrongMillisecondDateTime.Second); - RunWrongTest(c => c.NullableDateTime.Value.Second==WrongDateTime.Second); + RunWrongTest(c => c.DateTime.Second == WrongDateTime.Second); + RunWrongTest(c => c.MillisecondDateTime.Second == WrongMillisecondDateTime.Second); + RunWrongTest(c => c.NullableDateTime.Value.Second == WrongDateTime.Second); }); } [Test] public void ExtractMillisecondTest() { + Require.ProviderIsNot(StorageProvider.MySql); ExecuteInsideSession(() => { - RunTest(c => c.MillisecondDateTime.Millisecond==FirstMillisecondDateTime.Millisecond); - RunWrongTest(c => c.MillisecondDateTime.Second==WrongMillisecondDateTime.Millisecond); + RunTest(c => c.MillisecondDateTime.Millisecond == FirstMillisecondDateTime.Millisecond); + RunWrongTest(c => c.MillisecondDateTime.Second == WrongMillisecondDateTime.Millisecond); + }); + } + + [Test] + public void MysqlExtractMillisecondTest() + { + Require.ProviderIs(StorageProvider.MySql); + ExecuteInsideSession(() => { + var firstMillisecondDateTime = FirstMillisecondDateTime.FixDateTimeForProvider(StorageProvider.MySql); + RunTest(c => c.MillisecondDateTime.Millisecond == firstMillisecondDateTime.Millisecond); + RunWrongTest(c => c.MillisecondDateTime.Second == WrongMillisecondDateTime.Millisecond); }); } @@ -108,13 +120,13 @@ public void ExtractMillisecondTest() public void ExtractDateTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.Date==FirstDateTime.Date); - RunTest(c => c.MillisecondDateTime.Date==FirstMillisecondDateTime.Date); - RunTest(c => c.NullableDateTime.Value.Date==NullableDateTime.Date); + RunTest(c => c.DateTime.Date == FirstDateTime.Date); + RunTest(c => c.MillisecondDateTime.Date == FirstMillisecondDateTime.Date); + RunTest(c => c.NullableDateTime.Value.Date == NullableDateTime.Date); - RunWrongTest(c => c.DateTime.Date==WrongDateTime.Date); - RunWrongTest(c => c.MillisecondDateTime.Date==WrongMillisecondDateTime.Date); - RunWrongTest(c => c.NullableDateTime.Value.Date==WrongDateTime.Date); + RunWrongTest(c => c.DateTime.Date == WrongDateTime.Date); + RunWrongTest(c => c.MillisecondDateTime.Date == WrongMillisecondDateTime.Date); + RunWrongTest(c => c.NullableDateTime.Value.Date == WrongDateTime.Date); }); } @@ -122,13 +134,13 @@ public void ExtractDateTest() public void ExtractTimeOfDayTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.TimeOfDay==FirstDateTime.TimeOfDay); - RunTest(c => c.MillisecondDateTime.TimeOfDay==FirstMillisecondDateTime.TimeOfDay); - RunTest(c => c.NullableDateTime.Value.TimeOfDay==NullableDateTime.TimeOfDay); + RunTest(c => c.DateTime.TimeOfDay == FirstDateTime.TimeOfDay); + RunTest(c => c.MillisecondDateTime.TimeOfDay == FirstMillisecondDateTime.TimeOfDay); + RunTest(c => c.NullableDateTime.Value.TimeOfDay == NullableDateTime.TimeOfDay); - RunWrongTest(c => c.DateTime.TimeOfDay==WrongDateTime.TimeOfDay); - RunWrongTest(c => c.MillisecondDateTime.TimeOfDay==WrongMillisecondDateTime.TimeOfDay); - RunWrongTest(c => c.NullableDateTime.Value.TimeOfDay==WrongDateTime.TimeOfDay); + RunWrongTest(c => c.DateTime.TimeOfDay == WrongDateTime.TimeOfDay); + RunWrongTest(c => c.MillisecondDateTime.TimeOfDay == WrongMillisecondDateTime.TimeOfDay); + RunWrongTest(c => c.NullableDateTime.Value.TimeOfDay == WrongDateTime.TimeOfDay); }); } @@ -136,13 +148,13 @@ public void ExtractTimeOfDayTest() public void ExtractDayOfYearTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.DayOfYear==FirstDateTime.DayOfYear); - RunTest(c => c.MillisecondDateTime.DayOfYear==FirstMillisecondDateTime.DayOfYear); - RunTest(c => c.NullableDateTime.Value.DayOfYear==NullableDateTime.DayOfYear); + RunTest(c => c.DateTime.DayOfYear == FirstDateTime.DayOfYear); + RunTest(c => c.MillisecondDateTime.DayOfYear == FirstMillisecondDateTime.DayOfYear); + RunTest(c => c.NullableDateTime.Value.DayOfYear == NullableDateTime.DayOfYear); - RunWrongTest(c => c.DateTime.DayOfYear==WrongDateTime.DayOfYear); - RunWrongTest(c => c.MillisecondDateTime.DayOfYear==WrongMillisecondDateTime.DayOfYear); - RunWrongTest(c => c.NullableDateTime.Value.DayOfYear==WrongDateTime.DayOfYear); + RunWrongTest(c => c.DateTime.DayOfYear == WrongDateTime.DayOfYear); + RunWrongTest(c => c.MillisecondDateTime.DayOfYear == WrongMillisecondDateTime.DayOfYear); + RunWrongTest(c => c.NullableDateTime.Value.DayOfYear == WrongDateTime.DayOfYear); }); } @@ -150,13 +162,13 @@ public void ExtractDayOfYearTest() public void ExtractDayOfWeekTest() { ExecuteInsideSession(() => { - RunTest(c => c.DateTime.DayOfWeek==FirstDateTime.DayOfWeek); - RunTest(c => c.MillisecondDateTime.DayOfWeek==FirstMillisecondDateTime.DayOfWeek); - RunTest(c => c.NullableDateTime.Value.DayOfWeek==NullableDateTime.DayOfWeek); + RunTest(c => c.DateTime.DayOfWeek == FirstDateTime.DayOfWeek); + RunTest(c => c.MillisecondDateTime.DayOfWeek == FirstMillisecondDateTime.DayOfWeek); + RunTest(c => c.NullableDateTime.Value.DayOfWeek == NullableDateTime.DayOfWeek); - RunWrongTest(c => c.DateTime.DayOfWeek==WrongDateTime.DayOfWeek); - RunWrongTest(c => c.MillisecondDateTime.DayOfWeek==WrongMillisecondDateTime.DayOfWeek); - RunWrongTest(c => c.NullableDateTime.Value.DayOfWeek==WrongDateTime.DayOfWeek); + RunWrongTest(c => c.DateTime.DayOfWeek == WrongDateTime.DayOfWeek); + RunWrongTest(c => c.MillisecondDateTime.DayOfWeek == WrongMillisecondDateTime.DayOfWeek); + RunWrongTest(c => c.NullableDateTime.Value.DayOfWeek == WrongDateTime.DayOfWeek); }); } } diff --git a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/WhereTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/WhereTest.cs index 751a6b57bd..56dec921c9 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/WhereTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/WhereTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Groznov // Created: 2016.08.01 @@ -18,19 +18,20 @@ public class WhereTest : DateTimeBaseTest public void DateTimeWhereTest() { ExecuteInsideSession(() => { - WherePrivate(c => c.DateTime==FirstDateTime, c => c.Id); - WherePrivate(c => c.DateTime.Hour==FirstDateTime.Hour, c => c.Id); - WherePrivate(c => c.DateTime.Second==FirstDateTime.Second, c => c.Id); + WherePrivate(c => c.DateTime == FirstDateTime, c => c.Id); + WherePrivate(c => c.DateTime.Hour == FirstDateTime.Hour, c => c.Id); + WherePrivate(c => c.DateTime.Second == FirstDateTime.Second, c => c.Id); }); } [Test] public void MillisecondDateTimeWhereTest() { + Require.ProviderIsNot(StorageProvider.MySql); ExecuteInsideSession(() => { - WherePrivate(c => c.DateTime==FirstMillisecondDateTime, c => c.Id); - WherePrivate(c => c.DateTime.Hour==FirstMillisecondDateTime.Hour, c => c.Id); - WherePrivate(c => c.DateTime.Millisecond==FirstMillisecondDateTime.Millisecond, c => c.Id); + WherePrivate(c => c.DateTime == FirstMillisecondDateTime, c => c.Id); + WherePrivate(c => c.DateTime.Hour == FirstMillisecondDateTime.Hour, c => c.Id); + WherePrivate(c => c.DateTime.Millisecond == FirstMillisecondDateTime.Millisecond, c => c.Id); }); } @@ -38,10 +39,10 @@ public void MillisecondDateTimeWhereTest() public void NullableDateTimeWhereTest() { ExecuteInsideSession(() => { - WherePrivate(c => c.DateTime==FirstDateTime, c => c.Id); - WherePrivate(c => c.DateTime==null, c => c.Id); - WherePrivate(c => c.DateTime.HasValue && c.DateTime.Value.Hour==FirstDateTime.Hour, c => c.Id); - WherePrivate(c => c.DateTime.HasValue && c.DateTime.Value.Second==FirstDateTime.Second, c => c.Id); + WherePrivate(c => c.DateTime == FirstDateTime, c => c.Id); + WherePrivate(c => c.DateTime == null, c => c.Id); + WherePrivate(c => c.DateTime.HasValue && c.DateTime.Value.Hour == FirstDateTime.Hour, c => c.Id); + WherePrivate(c => c.DateTime.HasValue && c.DateTime.Value.Second == FirstDateTime.Second, c => c.Id); }); } From a9496b8bfc1bee7ff67944f1e696aece86042ed0 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 21:22:41 +0500 Subject: [PATCH 06/71] Fix domain building for IssueJira0778 --- .../IssueJira0778_PrefetchStackOverflow.cs | 182 +++++++++--------- 1 file changed, 88 insertions(+), 94 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs index 53f4f1644c..06a7a90352 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2019 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2019-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2019.10.24 @@ -43,6 +43,7 @@ protected override Domain BuildDomain(DomainConfiguration configuration) //try to avoid long population var domain = base.BuildDomain(firstTryConfig); ValidateTestData(domain); + return domain; } catch (SchemaSynchronizationException exception) { //schemas differ @@ -53,15 +54,16 @@ protected override Domain BuildDomain(DomainConfiguration configuration) // create so override existing schema and publish correct data isSchemaRecreated = true; } - var secondTry = configuration.Clone(); - secondTry.UpgradeMode = DomainUpgradeMode.Recreate; - return base.BuildDomain(secondTry); + var secondTryConfig = configuration.Clone(); + secondTryConfig.UpgradeMode = DomainUpgradeMode.Recreate; + return base.BuildDomain(secondTryConfig); } protected override void PopulateData() { - if (isSchemaRecreated) + if (!isSchemaRecreated) { return; + } PopulateEmployeeHierarchy(Domain); PopulateCustomers(Domain); @@ -73,7 +75,8 @@ protected override void PopulateData() [Test] public void MainTest() { - using (var session = Domain.OpenSession(new SessionConfiguration(SessionOptions.Default| SessionOptions.AutoActivation) {DefaultCommandTimeout = 3000})) + var sessionConfig = new SessionConfiguration(SessionOptions.Default | SessionOptions.AutoActivation) { DefaultCommandTimeout = 3000 }; + using (var session = Domain.OpenSession(sessionConfig)) using (var tx = session.OpenTransaction()) { ExecuteAsync(session); } @@ -91,7 +94,7 @@ public void OneLevelPrefetchTest() .Prefetch(a => a.SomeObject); var localResult = result.ToList(); - int count = 0; + var count = 0; session.Events.DbCommandExecuted += (sender, args) => count++; foreach (var aaaa in localResult) { Console.WriteLine("Reference {0}, Address {1}, Passport {2}", aaaa.Reference1, aaaa.Reference1.Address, aaaa.Reference1.Passport); @@ -122,7 +125,7 @@ public void TwoLevelPrefetchTest() ); var localResult = result.ToList(); - int count = 0; + var count = 0; session.Events.DbCommandExecuted += (sender, args) => count++; foreach (var aaaa in localResult) { Console.WriteLine("Reference {0}, Address {1}, Passport {2}", aaaa.Reference1, aaaa.Reference1.Address, aaaa.Reference1.Passport); @@ -166,7 +169,7 @@ public void ThreeLevelPrefetchTest() ); var localResult = result.ToList(); - int count = 0; + var count = 0; session.Events.DbCommandExecuted += (sender, args) => count++; foreach (var aaaa in localResult) { Console.WriteLine("Reference {0}, Address {1}, Passport {2}", aaaa.Reference1, aaaa.Reference1.Address, aaaa.Reference1.Passport); @@ -214,7 +217,7 @@ public void CyclicReferenceTest() .Prefetch(o => o.NextOperation) .ToList(); - int count = 0; + var count = 0; session.Events.DbCommandExecuted += (sender, args) => count++; foreach (var op in result) { Console.WriteLine("Prevoius operation {0}", op.PreviousOperation); @@ -232,7 +235,7 @@ private void ExecuteAsync(Session session) .ToList(); Assert.That(recipients.Count, Is.AtLeast(1000)); - int counter = 0; + var counter = 0; session.Events.DbCommandExecuted += (sender, args) => counter++; foreach (var recipient in recipients) { var contact = recipient.Contact; @@ -253,15 +256,16 @@ private static void ValidateTestData(Domain domain) var Cs = session.Query.ExecuteDelayed(q => q.All().Count()); var isValid = recipientCount.Value==CustomerCount && - employeeCount.Value== 45 && + employeeCount.Value == 45 && boss.Value != null && contactCount.Value > CustomerCount * 3 && As.Value == 10 && Bs.Value == 100 && Cs.Value == 1000; - if (!isValid) + if (!isValid) { throw new TestDataInvalidException(); + } } } @@ -273,58 +277,58 @@ private static void PopulateEmployeeHierarchy(Domain domain) var gm = new Employee(session, "General", "Manager"); var ipDirector = new Employee(session, "Investment & Placement", "Director"); var pManager = new Employee(session, "Placement", "Director"); - new Employee(session, "Placement", "Staff #1"); - new Employee(session, "Placement", "Staff #2"); - new Employee(session, "Placement", "Staff #3"); + _ = new Employee(session, "Placement", "Staff #1"); + _ = new Employee(session, "Placement", "Staff #2"); + _ = new Employee(session, "Placement", "Staff #3"); var iManager = new Employee(session, "Investment", "Manager"); - new Employee(session, "Investment", "Staff #1"); - new Employee(session, "Investment", "Staff #2"); - new Employee(session, "Investment", "Staff #3"); + _ = new Employee(session, "Investment", "Staff #1"); + _ = new Employee(session, "Investment", "Staff #2"); + _ = new Employee(session, "Investment", "Staff #3"); var bdsManager = new Employee(session, "Business Development", "S.Manager"); - new Employee(session, "Projects Marketing and Exhibition Team", "Member #1"); - new Employee(session, "Projects Marketing and Exhibition Team", "Member #2"); - new Employee(session, "Projects Marketing and Exhibition Team", "Member #3"); + _ = new Employee(session, "Projects Marketing and Exhibition Team", "Member #1"); + _ = new Employee(session, "Projects Marketing and Exhibition Team", "Member #2"); + _ = new Employee(session, "Projects Marketing and Exhibition Team", "Member #3"); - new Employee(session, "Projects Marketing and Exhibition Team", "Member #1"); - new Employee(session, "Projects Marketing and Exhibition Team", "Member #2"); - new Employee(session, "Projects Marketing and Exhibition Team", "Member #3"); + _ = new Employee(session, "Projects Marketing and Exhibition Team", "Member #1"); + _ = new Employee(session, "Projects Marketing and Exhibition Team", "Member #2"); + _ = new Employee(session, "Projects Marketing and Exhibition Team", "Member #3"); var pdDirector = new Employee(session, "Project Development", "Director"); - new Employee(session, "Project", "Architect #1"); - new Employee(session, "Project", "Architect #2"); - new Employee(session, "Project", "Architect #3"); + _ = new Employee(session, "Project", "Architect #1"); + _ = new Employee(session, "Project", "Architect #2"); + _ = new Employee(session, "Project", "Architect #3"); - new Employee(session, "Project", "Manager #1"); - new Employee(session, "Project", "Manager #2"); - new Employee(session, "Project", "Manager #3"); + _ = new Employee(session, "Project", "Manager #1"); + _ = new Employee(session, "Project", "Manager #2"); + _ = new Employee(session, "Project", "Manager #3"); var hraDirector = new Employee(session, "HR & Admin", "Director"); - new Employee(session, "HR", "Staff #1"); - new Employee(session, "HR", "Staff #2"); - new Employee(session, "HR", "Staff #3"); + _ = new Employee(session, "HR", "Staff #1"); + _ = new Employee(session, "HR", "Staff #2"); + _ = new Employee(session, "HR", "Staff #3"); - new Employee(session, "Admin", "Staff #1"); - new Employee(session, "Admin", "Staff #2"); - new Employee(session, "Admin", "Staff #3"); + _ = new Employee(session, "Admin", "Staff #1"); + _ = new Employee(session, "Admin", "Staff #2"); + _ = new Employee(session, "Admin", "Staff #3"); - new Employee(session, "Support", "Serviceman #1"); - new Employee(session, "Support", "Serviceman #2"); - new Employee(session, "Support", "Serviceman #3"); + _ = new Employee(session, "Support", "Serviceman #1"); + _ = new Employee(session, "Support", "Serviceman #2"); + _ = new Employee(session, "Support", "Serviceman #3"); var fitDirector = new Employee(session, "Finance & IT", "Director"); var chiefAccountant = new Employee(session, "Chief", "Accountant"); - new Employee(session, "Accountant", "Clerk #1"); - new Employee(session, "Accountant", "Clerk #2"); - new Employee(session, "Accountant", "Clerk #3"); - new Employee(session, "Accountant", "Clerk #4"); - new Employee(session, "Accountant", "Clerk #5"); + _ = new Employee(session, "Accountant", "Clerk #1"); + _ = new Employee(session, "Accountant", "Clerk #2"); + _ = new Employee(session, "Accountant", "Clerk #3"); + _ = new Employee(session, "Accountant", "Clerk #4"); + _ = new Employee(session, "Accountant", "Clerk #5"); - new Employee(session, "IT","Administrator #1"); - new Employee(session, "IT", "Administrator #2"); - new Employee(session, "IT", "Administrator #3"); + _ = new Employee(session, "IT","Administrator #1"); + _ = new Employee(session, "IT", "Administrator #2"); + _ = new Employee(session, "IT", "Administrator #3"); tx.Complete(); } @@ -334,11 +338,11 @@ private static void PopulateCustomers(Domain domain) { using (var session = domain.OpenSession()) using (var tx = session.OpenTransaction()) { - for (int i = 0; i < CustomerCount; i++) { + for (var i = 0; i < CustomerCount; i++) { var customer = new Customer(session, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); - new Contact(session, customer, ContactType.Email, ContactGenerator.GetEmail()); - new Contact(session, customer, ContactType.Fax, ContactGenerator.GetPhone()); - new Contact(session, customer, ContactType.Phone, ContactGenerator.GetPhone()); + _ = new Contact(session, customer, ContactType.Email, ContactGenerator.GetEmail()); + _ = new Contact(session, customer, ContactType.Fax, ContactGenerator.GetPhone()); + _ = new Contact(session, customer, ContactType.Phone, ContactGenerator.GetPhone()); } tx.Complete(); } @@ -349,9 +353,9 @@ private static void PopulateContactsForEmployees(Domain domain) using (var session = domain.OpenSession()) using (var tx = session.OpenTransaction()) { foreach (var employee in session.Query.All()) { - new Contact(session, employee, ContactType.Email, ContactGenerator.GetEmail()) {Active = true}; - new Contact(session, employee, ContactType.Fax, ContactGenerator.GetPhone()) {Active = true}; - new Contact(session, employee, ContactType.Phone, ContactGenerator.GetPhone()) {Active= true}; + _ = new Contact(session, employee, ContactType.Email, ContactGenerator.GetEmail()) { Active = true }; + _ = new Contact(session, employee, ContactType.Fax, ContactGenerator.GetPhone()) { Active = true }; + _ = new Contact(session, employee, ContactType.Phone, ContactGenerator.GetPhone()) { Active= true }; } tx.Complete(); } @@ -359,13 +363,13 @@ private static void PopulateContactsForEmployees(Domain domain) public static void PopulateRecipients(Domain domain) { - Random random = new Random(); + var random = new Random(); using (var session = domain.OpenSession()) using (var tx = session.OpenTransaction()) { var customers = session.Query.All().ToArray(); foreach (var customer in customers) { var contactsToChoose = customer.Contacts.ToArray(); - new Recipient(session, new Audience(session)) { + _ = new Recipient(session, new Audience(session)) { Contact = contactsToChoose[random.Next(0, contactsToChoose.Length)], Active = true, Data = Guid.NewGuid().ToString(), @@ -380,7 +384,7 @@ public static void PopulateTestHierarchy(Domain domain) { using (var session = domain.OpenSession()) using (var tx = session.OpenTransaction()) { - for (int i = 0; i < 10; i++) { + for (var i = 0; i < 10; i++) { var aaaa = new AAAA { Reference1 = new ReferenceEntity1 { Reference = new ReferenceEntity10(), @@ -429,7 +433,7 @@ public static void PopulateTestHierarchy(Domain domain) }, SomeObject = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()) }; - for (int j = 0; j < 10; j++) { + for (var j = 0; j < 10; j++) { var bbbb = new BBBB { Reference4 = new ReferenceEntity4() { Reference = new ReferenceEntity10(), @@ -478,7 +482,7 @@ public static void PopulateTestHierarchy(Domain domain) }, SomeObject = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()) }; - for (int k = 0; k < 10; k++) { + for (var k = 0; k < 10; k++) { var cccc = new CCCC { Reference7 = new ReferenceEntity7 { Reference = new ReferenceEntity10(), @@ -527,9 +531,9 @@ public static void PopulateTestHierarchy(Domain domain) }, SomeObject = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()) }; - bbbb.CCCCs.Add(cccc); + _ = bbbb.CCCCs.Add(cccc); } - aaaa.Bbbbs.Add(bbbb); + _ = aaaa.Bbbbs.Add(bbbb); } } tx.Complete(); @@ -542,27 +546,22 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0778_PrefetchStackOverflowModel { public class ContactGenerator { - private static Random Random = new Random(); + private static readonly Random Randomizer = new Random(); public const string Template = "+7({0}){1}-{2}-{3}"; public readonly static string[] Hosts = new[] {"@gimail.com", "@jahoo.com", "@inlook.com", "@tindax.ru"}; public static string GetEmail() - { - return Guid.NewGuid().ToString().Replace('-', '_') + Hosts[Random.Next(0, 4)]; - } + => Guid.NewGuid().ToString().Replace('-', '_') + Hosts[Randomizer.Next(0, 4)]; - public static string GetFax() - { - return GetPhone(); - } + public static string GetFax() => GetPhone(); public static string GetPhone() { - var code = Random.Next(900, 950); - var block1 = Random.Next(100, 1000); - var block2 = Random.Next(10, 100); - var block3 = Random.Next(10, 100); + var code = Randomizer.Next(900, 950); + var block1 = Randomizer.Next(100, 1000); + var block2 = Randomizer.Next(10, 100); + var block3 = Randomizer.Next(10, 100); return string.Format(Template, code, block1, block2, block3); } } @@ -570,9 +569,7 @@ public static string GetPhone() public static class Extensions { public static IQueryable Active(this IQueryable source) - { - return source.Where(e => e.Active); - } + => source.Where(e => e.Active); } public enum ContactType @@ -674,7 +671,7 @@ public class Contact : BusinessEntityBase [Field] public bool MarketingUpdatesEnabled { get; set; } - [Field(DefaultSqlExpression = "GETUTCDATE()")] + [Field] public DateTime ModifiedOn { get; set; } public Contact(Session session, IHasContacts owner, ContactType type, string value) @@ -684,6 +681,7 @@ public Contact(Session session, IHasContacts owner, ContactType type, string val Type = type; MarketingUpdatesEnabled = true; Value = value; + ModifiedOn = DateTime.UtcNow; } } @@ -700,7 +698,7 @@ public class Employee : BusinessEntityBase, IHasContacts public EntitySet Contacts { get; private set; } public Employee(Session session, string firstName, string lastName) - :base(session) + : base(session) { FirstName = firstName; LastName = lastName; @@ -720,7 +718,7 @@ public class Customer : BusinessEntityBase, IHasContacts public EntitySet Contacts { get; private set; } public Customer(Session session, string firstName, string lastName) - :base(session) + : base(session) { FistName = firstName; LastName = lastName; @@ -988,14 +986,13 @@ public class Address : Structure public override string ToString() { - var builder = new StringBuilder(); - - builder.Append(Building); - builder.Append(Street).Append(", "); - builder.Append(City).Append(", "); - builder.Append(Region).Append(", "); - builder.Append(Index).Append(", "); - builder.Append(Country); + var builder = new StringBuilder() + .Append(Building) + .Append($"{Street}, ") + .Append($"{City}, ") + .Append($"{Region}, ") + .Append($"{Index}, ") + .Append(Country); return builder.ToString(); } @@ -1009,9 +1006,6 @@ public class PassportData : Structure [Field(Length = 128)] public string Number { get; set; } - public override string ToString() - { - return Series + " " + Number; - } + public override string ToString() => $"{Series} {Number}"; } } \ No newline at end of file From 44d7c3e8ebd568e1aa2b711d9291411eeba8c32b Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 21:30:14 +0500 Subject: [PATCH 07/71] Issue0624 test improvements - MySQL is excluded from required providers - MainTest() was split to several tests per each tested query --- .../Issue0624_EntitySetSubqueryError.cs | 54 ++++++++++++++----- 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs index d649453e00..376ecacd8f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2010-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2010.03.24 @@ -70,7 +70,7 @@ public class Issue0624_EntitySetSubqueryError : AutoBuildTest protected override void CheckRequirements() { base.CheckRequirements(); - Require.ProviderIsNot(StorageProvider.Oracle); + Require.ProviderIsNot(StorageProvider.Oracle | StorageProvider.MySql); } protected override DomainConfiguration BuildConfiguration() @@ -81,7 +81,7 @@ protected override DomainConfiguration BuildConfiguration() } [Test] - public void MainTest() + public void Test01() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { @@ -92,17 +92,47 @@ public void MainTest() session.SaveChanges(); var ids = new[] { controlId, messageId }; - var itemsX = session.Query.All().Where(a => a.Messages.Select(b => b.Id).Any(id => ids.Contains(id))).ToList(); - Assert.AreEqual(1, itemsX.Count); - Assert.AreSame(control, itemsX[0]); - var itemsA = session.Query.All().Where(a => ids.Any(id => a.Messages.Select(b => b.Id).Contains(id))).ToList(); - Assert.AreEqual(1, itemsA.Count); - Assert.AreSame(control, itemsA[0]); var itemsB = session.Query.All().Where(a => ids.ContainsAny(a.Messages.Select(b => b.Id))).ToList(); Assert.AreEqual(1, itemsB.Count); Assert.AreSame(control, itemsB[0]); t.Complete(); - } + } + } + + [Test] + public void Test02() + { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var controlId = Guid.NewGuid(); + var messageId = Guid.NewGuid(); + var control = new Control(controlId); + var message = new ControlMessage(messageId) { Owner = control }; + session.SaveChanges(); + + var ids = new[] { controlId, messageId }; + var itemsA = session.Query.All().Where(a => ids.Any(id => a.Messages.Select(b => b.Id).Contains(id))).ToList(); + Assert.AreEqual(1, itemsA.Count); + Assert.AreSame(control, itemsA[0]); + } + } + + [Test] + public void Test03() + { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var controlId = Guid.NewGuid(); + var messageId = Guid.NewGuid(); + var control = new Control(controlId); + var message = new ControlMessage(messageId) { Owner = control }; + session.SaveChanges(); + + var ids = new[] { controlId, messageId }; + var itemsX = session.Query.All().Where(a => a.Messages.Select(b => b.Id).Any(id => ids.Contains(id))).ToList(); + Assert.AreEqual(1, itemsX.Count); + Assert.AreSame(control, itemsX[0]); + } } } } \ No newline at end of file From b17cce6d11e0b611b91cae4f7ca45b881771d658 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 15 Mar 2021 21:35:11 +0500 Subject: [PATCH 08/71] Fix DateTime.DayOfWeek compiler Most RDBMSs have the same values for days of week as .Net, but not MySQL. It has the same order by Int values assigned with days of week start with 1. --- .../Expressions/MemberCompilers/DateTimeCompilers.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/DateTimeCompilers.cs b/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/DateTimeCompilers.cs index ab863b0299..df617de4e7 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/DateTimeCompilers.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/DateTimeCompilers.cs @@ -74,7 +74,15 @@ public static SqlExpression DateTimeDate(SqlExpression _this) [Compiler(typeof(DateTime), "DayOfWeek", TargetKind.PropertyGet)] public static SqlExpression DateTimeDayOfWeek(SqlExpression _this) { - return ExpressionTranslationHelpers.ToInt(SqlDml.Extract(SqlDateTimePart.DayOfWeek, _this)); + var baseExpression = ExpressionTranslationHelpers.ToInt(SqlDml.Extract(SqlDateTimePart.DayOfWeek, _this)); + var context = ExpressionTranslationContext.Current; + if (context == null) { + return baseExpression; + } + if (context.ProviderInfo.ProviderName == WellKnown.Provider.MySql) { + return baseExpression - 1; //Mysql starts days of week from 1 unlike in .Net. + } + return baseExpression; } [Compiler(typeof(DateTime), "DayOfYear", TargetKind.PropertyGet)] From 52482ddd63812b7385165343d20484bf3d7b9f39 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 16 Mar 2021 19:21:10 +0500 Subject: [PATCH 09/71] Dynamically remove DefaultValue declaration MySQL does not support for default values for string fields with length longer than 4000 --- .../Upgrade/NewSkip/Model.cs | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs index ba10778152..442542e8da 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.02.24 @@ -9,6 +9,8 @@ using System.Security.Cryptography; using System.Text; using Xtensive.Core; +using Xtensive.Orm.Building; +using Xtensive.Orm.Building.Definitions; using Xtensive.Orm.Model; namespace Xtensive.Orm.Tests.Upgrade.NewSkip.Model @@ -459,6 +461,24 @@ public ComplexKeyEntity(int key1, int key2) { } } + + public class MySQLModelFixModule : IModule + { + public void OnBuilt(Domain domain) + { + } + + public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) + { + var provider = context.Configuration.ConnectionInfo.ConnectionString ?? context.Configuration.ConnectionInfo.ConnectionUrl.Protocol; + if (provider != WellKnown.Provider.MySql) { + return; + } + var typeDef = model.Types[typeof(X)]; + var problemField = typeDef.Fields["FLongString"]; + problemField.DefaultValue = null; + } + } } namespace Laptops From 4915a1a945627a3a2821daa8ab06ed7065f0bf33 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 16 Mar 2021 19:36:34 +0500 Subject: [PATCH 10/71] Mysql: Remove some types from cast-required list --- .../Sql.Drivers.MySql/v5_0/TypeMapper.cs | 21 +++++++------------ 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/v5_0/TypeMapper.cs b/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/v5_0/TypeMapper.cs index c28298917a..a3550e672e 100644 --- a/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/v5_0/TypeMapper.cs +++ b/Orm/Xtensive.Orm.MySql/Sql.Drivers.MySql/v5_0/TypeMapper.cs @@ -1,38 +1,31 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Malisa Ncube // Created: 2011.02.25 using System; using System.Data; using System.Data.Common; +using System.Linq; using System.Security; namespace Xtensive.Sql.Drivers.MySql.v5_0 { internal class TypeMapper : Sql.TypeMapper { + private static readonly Type[] CastRequiredTypes = new[] { typeof(Guid), typeof(TimeSpan), typeof(byte[]) }; + /// public override bool IsParameterCastRequired(Type type) { switch (Type.GetTypeCode(type)) { - case TypeCode.Byte: - case TypeCode.SByte: - case TypeCode.Int16: - case TypeCode.UInt16: case TypeCode.Single: case TypeCode.Double: case TypeCode.DateTime: return true; } - if (type==typeof (Guid)) - return true; - if (type==typeof (TimeSpan)) - return true; - if (type==typeof (byte[])) - return true; - return false; + return CastRequiredTypes.Contains(type); } /// From 1bb8a253994093d352c56323fca46d366f5a1fa2 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 16 Mar 2021 19:41:52 +0500 Subject: [PATCH 11/71] Change test name to Frank --- Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs b/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs index ad382a65c5..202a80cebc 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs @@ -64,14 +64,14 @@ public void FirstTest() [Test] public void FirstPredicateTest() { - var customer = Session.Query.All().First(c => c.FirstName == "Luis"); + var customer = Session.Query.All().First(c => c.FirstName == "Frank"); Assert.IsNotNull(customer); } [Test] public void WhereFirstTest() { - var customer = Session.Query.All().Where(c => c.FirstName == "Luis").First(); + var customer = Session.Query.All().Where(c => c.FirstName == "Frank").First(); Assert.IsNotNull(customer); } @@ -85,7 +85,7 @@ public void FirstOrDefaultTest() [Test] public void FirstOrDefaultPredicateTest() { - var customer = Session.Query.All().FirstOrDefault(c => c.FirstName == "Luis"); + var customer = Session.Query.All().FirstOrDefault(c => c.FirstName == "Frank"); Assert.IsNotNull(customer); customer = Session.Query.All().FirstOrDefault(c => c.FirstName == "Aaron"); Assert.IsNotNull(customer); @@ -96,7 +96,7 @@ public void FirstOrDefaultPredicateTest() [Test] public void WhereFirstOrDefaultTest() { - var customer = Session.Query.All().Where(c => c.FirstName == "Luis").FirstOrDefault(); + var customer = Session.Query.All().Where(c => c.FirstName == "Frank").FirstOrDefault(); Assert.IsNotNull(customer); customer = Session.Query.All().Where(c => c.FirstName == "Aaron").FirstOrDefault(); Assert.IsNotNull(customer); @@ -115,7 +115,7 @@ public void SinglePredicateTest() { var customer = Session.Query.All().Single(c => c.FirstName == "Aaron"); Assert.IsNotNull(customer); - _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Luis").Single()); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Frank").Single()); _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "ThereIsNoSuchFirstName").Single()); } @@ -124,7 +124,7 @@ public void WhereSingleTest() { var customer = Session.Query.All().Where(c => c.FirstName == "Aaron").Single(); Assert.IsNotNull(customer); - _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Luis").Single()); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Frank").Single()); _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "ThereIsNoSuchFirstName").Single()); } @@ -139,7 +139,7 @@ public void SingleOrDefaultPredicateTest() { var customer = Session.Query.All().SingleOrDefault(c => c.FirstName == "Aaron"); Assert.IsNotNull(customer); - _ = Assert.Throws(() => Session.Query.All().SingleOrDefault(c => c.FirstName == "Luis")); + _ = Assert.Throws(() => Session.Query.All().SingleOrDefault(c => c.FirstName == "Frank")); customer = Session.Query.All().SingleOrDefault(c => c.FirstName == "ThereIsNoSuchFirstName"); Assert.IsNull(customer); } @@ -149,7 +149,7 @@ public void WhereSingleOrDefaultTest() { var customer = Session.Query.All().Where(c => c.FirstName == "Aaron").SingleOrDefault(); Assert.IsNotNull(customer); - _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Luis").SingleOrDefault()); + _ = Assert.Throws(() => Session.Query.All().Where(c => c.FirstName == "Frank").SingleOrDefault()); customer = Session.Query.All().Where(c => c.FirstName == "ThereIsNoSuchFirstName").SingleOrDefault(); Assert.IsNull(customer); } From 225c865d8394071c46f14e23f20f6f1558d4ecb2 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 16 Mar 2021 19:51:21 +0500 Subject: [PATCH 12/71] Change length of indexed string fields MySQL does not like long strings to be indexed --- .../Issues/Issue0559_EntitySetQueryError.cs | 13 ++++++------- ...ra0641_IndexFilterExpressionTranslationBug.cs | 14 ++++++++------ .../Model/IndexedStructureFieldTest.cs | 10 +++++----- .../Model/InheritanceSchemaTest.cs | 16 ++++++++-------- 4 files changed, 27 insertions(+), 26 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs index e725169840..41acd66fab 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.12.23 @@ -22,7 +22,7 @@ public class Topic : Entity [Field, Key] public long Id { get; private set; } - [Field] + [Field(Length = 25)] public string Name { get; set; } [Field, Association(OnTargetRemove = OnRemoveAction.Clear)] @@ -41,7 +41,7 @@ public class Subscription : Entity [Field, Key(1)] public long LastEventId { get; private set; } - [Field(Length = 300)] + [Field(Length = 25)] public string ApplicationName { get; set; } [Field] @@ -73,9 +73,8 @@ public void MainTest() var ApplicationName = "Name"; var defaultTopic = new Topic() { Name = topicName }; var subscription = new Subscription(1, 1) {ApplicationName = ApplicationName}; - defaultTopic.Subscriptions.Add(subscription); + _ = defaultTopic.Subscriptions.Add(subscription); - var subTopic = (from topic in session.Query.All() where topic.Name == topicName select topic).SingleOrDefault(); var subscriptions = subTopic.Subscriptions; var result = from sub in subscriptions where sub.ApplicationName == ApplicationName select sub; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs index c6dddb608e..542edeca8e 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.08.09 @@ -20,7 +20,7 @@ public class BandwidthCall : Entity [Field, Key] public int Id { get; private set; } - [Field] + [Field(Length = 250)] public string Text { get; set; } [Field] @@ -29,9 +29,11 @@ public class BandwidthCall : Entity [Field] public DirectionEnum Direction { get; set; } +#pragma warning disable IDE0051 // Remove unused private members private static Expression> NotBilledCalls() +#pragma warning restore IDE0051 // Remove unused private members { - return e => e.IsBilled==false && (e.Direction).In(DirectionEnum.FirstIn, DirectionEnum.FirstOut); + return e => e.IsBilled == false && (e.Direction).In(DirectionEnum.FirstIn, DirectionEnum.FirstOut); } } @@ -71,7 +73,7 @@ public void MainTest() configuration.UpgradeMode = DomainUpgradeMode.Recreate; Domain domain = null; - Assert.DoesNotThrow(()=> domain = Domain.Build(configuration)); + Assert.DoesNotThrow(() => domain = Domain.Build(configuration)); if (domain!=null) domain.Dispose(); } diff --git a/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs b/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs index a5a7e2c6c3..e147b21463 100644 --- a/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2012 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2012-2021 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 // Created: 2012.05.11 @@ -28,7 +28,7 @@ public interface IHierarchical2 : IHierarchical public class Hierarchy : Structure { - [Field(Indexed = true, Length = 300)] + [Field(Indexed = true, Length = 250)] public string Name { get; set; } } @@ -57,7 +57,7 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.NamingConvention.NamingRules = NamingRules.UnderscoreDots; - configuration.Types.Register(typeof (Hierarchy).Assembly, typeof (Hierarchy).Namespace); + configuration.Types.Register(typeof(Hierarchy).Assembly, typeof(Hierarchy).Namespace); return configuration; } diff --git a/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs b/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs index 390e95bc26..ae90342c9a 100644 --- a/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2007-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kochetov // Created: 2007.11.30 @@ -18,14 +18,14 @@ namespace Xtensive.Orm.Tests.Model.InheritanceSchemaModel [Index("Name")] public interface IHasName : IEntity { - [Field(Length = 1000)] + [Field(Length = 250)] string Name { get; set; } } [Index("Name")] public interface IHasName2 : IEntity { - [Field(Length = 1000)] + [Field(Length = 250)] string Name { get; set; } } @@ -62,7 +62,7 @@ public class D : C, ICreature { public string Name { get; set; } - [Field(Length = 1000)] + [Field(Length = 250)] public virtual string Tag { get; set; } } @@ -188,7 +188,7 @@ public class ConcreteTableInheritanceTest : InheritanceSchemaTestBase { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration configuration = base.BuildConfiguration(); + var configuration = base.BuildConfiguration(); ConcreteTableInheritanceBuilder.IsEnabled = true; SingleTableInheritanceBuilder.IsEnabled = false; return configuration; @@ -205,7 +205,7 @@ public class SingleTableInheritanceTest : InheritanceSchemaTestBase { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration configuration = base.BuildConfiguration(); + var configuration = base.BuildConfiguration(); ConcreteTableInheritanceBuilder.IsEnabled = false; SingleTableInheritanceBuilder.IsEnabled = true; return configuration; From 45af1aa741ee2162205c3de5a3875f5a5295796a Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 16 Mar 2021 20:01:53 +0500 Subject: [PATCH 13/71] Improve DateTime resolution cut down for tests --- .../StorageProviderVersion.cs | 18 +++++++++++++--- .../TestHelper.cs | 5 +++-- ...ueJira0593_AggregateForSingleColumnTest.cs | 8 +++---- .../DateTime/OperationsTest.cs | 21 +++++++++++++++++++ .../DateTime/PartsExtractionTest.cs | 2 +- 5 files changed, 44 insertions(+), 10 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests.Framework/StorageProviderVersion.cs b/Orm/Xtensive.Orm.Tests.Framework/StorageProviderVersion.cs index d04b4445e4..2d5202ad86 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/StorageProviderVersion.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/StorageProviderVersion.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2010-2021 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 // Created: 2010.02.11 @@ -14,6 +14,10 @@ public static class StorageProviderVersion public static Version SqlServer2008 = new Version(10, 0); public static Version SqlServer2008R2 = new Version(10, 50); public static Version SqlServer2012 = new Version(11, 0); + public static Version SqlServer2014 = new Version(12, 0); + public static Version SqlServer2016 = new Version(13, 0); + public static Version SqlServer2017 = new Version(14, 0); + public static Version SqlServer2019 = new Version(15, 0); public static Version Oracle09 = new Version(9, 0); public static Version Oracle10 = new Version(10, 0); @@ -24,5 +28,13 @@ public static class StorageProviderVersion public static Version PostgreSql82 = new Version(8, 2); public static Version PostgreSql83 = new Version(8, 3); public static Version PostgreSql84 = new Version(8, 4); + public static Version PostgreSql90 = new Version(9, 0); + public static Version PostgreSql91 = new Version(9, 1); + public static Version PostgreSql92 = new Version(9, 2); + public static Version PostgreSql100 = new Version(10, 0); + public static Version PostgreSql110 = new Version(11, 0); + + public static Version MySql55 = new Version(5, 5); + public static Version MySql56 = new Version(5, 6); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs b/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs index deaa2082f2..c4bc8884bf 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/TestHelper.cs @@ -56,12 +56,13 @@ public static System.Configuration.Configuration GetConfigurationForAssembly(thi /// The value to fix. /// Type of provider. /// New value with less resolution if requires it or untouched if the provider doesn't - public static DateTime FixDateTimeForProvider(this DateTime origin, StorageProvider provider) + public static DateTime FixDateTimeForProvider(this DateTime origin, StorageProviderInfo providerInfo) { long? divider; + var provider = providerInfo.Provider; switch (provider) { case StorageProvider.MySql: - divider = 10000000; + divider = providerInfo.Info.StorageVersion < StorageProviderVersion.MySql56 ? 10000000 : 10; break; case StorageProvider.Firebird: divider = 1000; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs index 769587ad30..55deb15439 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs @@ -675,10 +675,10 @@ private static void CheckQueryable(IQueryable query) private static void CheckQueryable(IQueryable query) { var localArray = query.ToArray(); - Assert.AreEqual(localArray.Min().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Min(c => c)); - Assert.AreEqual(localArray.Min().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Min()); - Assert.AreEqual(localArray.Max().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Max(c => c)); - Assert.AreEqual(localArray.Max().FixDateTimeForProvider(StorageProviderInfo.Instance.Provider), query.Max()); + Assert.AreEqual(localArray.Min().FixDateTimeForProvider(StorageProviderInfo.Instance), query.Min(c => c)); + Assert.AreEqual(localArray.Min().FixDateTimeForProvider(StorageProviderInfo.Instance), query.Min()); + Assert.AreEqual(localArray.Max().FixDateTimeForProvider(StorageProviderInfo.Instance), query.Max(c => c)); + Assert.AreEqual(localArray.Max().FixDateTimeForProvider(StorageProviderInfo.Instance), query.Max()); Assert.AreEqual(localArray.Count(), query.Count()); } diff --git a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs index 2c7197404d..b0b2bb46d7 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/OperationsTest.cs @@ -179,6 +179,7 @@ public void MinusTimeSpanTest() [Test] public void MinusDateTimeTest() { + Require.ProviderIsNot(StorageProvider.MySql); ExecuteInsideSession(() => { RunTest(c => c.DateTime - SecondDateTime == FirstDateTime - SecondDateTime); RunTest(c => c.MillisecondDateTime - SecondDateTime == FirstMillisecondDateTime - SecondDateTime); @@ -189,5 +190,25 @@ public void MinusDateTimeTest() RunWrongTest(c => c.NullableDateTime - SecondDateTime == NullableDateTime - WrongDateTime); }); } + + [Test] + public void MysqlMinisDateTimeTest() + { + Require.ProviderIs(StorageProvider.MySql); + ExecuteInsideSession(() => { + var firstDateTime = FirstDateTime.FixDateTimeForProvider(StorageProviderInfo.Instance); + var firstMillisecondDateTime = FirstMillisecondDateTime.FixDateTimeForProvider(StorageProviderInfo.Instance); + var secondDateTime = SecondDateTime.FixDateTimeForProvider(StorageProviderInfo.Instance); + var nullableDateTime = NullableDateTime.FixDateTimeForProvider(StorageProviderInfo.Instance); + + RunTest(c => c.DateTime - secondDateTime == firstDateTime - secondDateTime); + RunTest(c => c.MillisecondDateTime - secondDateTime == firstMillisecondDateTime - secondDateTime); + RunTest(c => c.NullableDateTime - secondDateTime == nullableDateTime - secondDateTime); + + RunWrongTest(c => c.DateTime - secondDateTime == firstDateTime - WrongDateTime); + RunWrongTest(c => c.MillisecondDateTime - secondDateTime == firstMillisecondDateTime - WrongDateTime); + RunWrongTest(c => c.NullableDateTime - secondDateTime == nullableDateTime - WrongDateTime); + }); + } } } diff --git a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs index 790f7c272c..4cfa15f988 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DateTimeAndDateTimeOffset/DateTime/PartsExtractionTest.cs @@ -110,7 +110,7 @@ public void MysqlExtractMillisecondTest() { Require.ProviderIs(StorageProvider.MySql); ExecuteInsideSession(() => { - var firstMillisecondDateTime = FirstMillisecondDateTime.FixDateTimeForProvider(StorageProvider.MySql); + var firstMillisecondDateTime = FirstMillisecondDateTime.FixDateTimeForProvider(StorageProviderInfo.Instance); RunTest(c => c.MillisecondDateTime.Millisecond == firstMillisecondDateTime.Millisecond); RunWrongTest(c => c.MillisecondDateTime.Second == WrongMillisecondDateTime.Millisecond); }); From 46686937710095dd11d925cde80cc6ddeb5ad067 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 17 Mar 2021 17:31:43 +0500 Subject: [PATCH 14/71] Switch extensions tests to Tests.Framework Remove copies of some classes that already exist in the tests framework like DomainConfigurationFactory or TestConfiguration and made tests of extensions be based on single AutoBuildTest from the tests framework. + minor changes --- Extensions/TestCommon/CommonModelTest.cs | 55 +--- .../TestCommon/DomainConfigurationFactory.cs | 22 -- .../HasAccessToConfigurationTest.cs | 22 -- Extensions/TestCommon/TestConfiguration.cs | 100 ------- .../TestCommon/Tests/TestConfigurationTest.cs | 3 +- ...oBuildTest.cs => BulkOperationBaseTest.cs} | 8 +- .../ContainsTest.cs | 12 +- .../Extensions.cs | 2 +- ...angeFieldWhichDefinedInAncestorClassBug.cs | 8 +- ...ira0565_IgnoringTakeMethodOnTranslation.cs | 85 +++--- .../Issues/JoinedTableAsSourceForDelete.cs | 7 +- .../Other.cs | 6 +- .../ReferenceFields.cs | 2 +- .../Structures.cs | 247 ++++++++++-------- .../AccessToLocalizationOnUpgrade.cs | 15 +- .../CurrentThreadTest.cs | 2 +- .../DirectEditTest.cs | 43 ++- ...toBuildTest.cs => LocalizationBaseTest.cs} | 23 +- .../LocalizationScopeTest.cs | 60 ++--- .../Model/Page.cs | 6 +- .../Model/PageLocalization.cs | 6 +- .../MultipleNodesTest.cs | 4 +- .../QueryTests.cs | 78 +++--- .../AutoBuildTest.cs | 28 -- .../Extensions.cs | 11 +- .../ReprocessingBaseTest.cs | 27 ++ .../Tests/Other.cs | 47 ++-- .../Tests/Reprocessing.cs | 117 +++++---- .../AutoBuildTest.cs | 109 -------- .../SecurityTestBase.cs | 81 ++++++ .../Tests/AuthenticationTests.cs | 38 ++- .../Tests/ConfigurationTests.cs | 7 +- .../Tests/HashingServicesTests.cs | 10 +- .../Tests/ImpersonationContextTests.cs | 242 +++++++++-------- .../Tests/PermissionSetTests.cs | 74 +++--- .../AutoBuildTest.cs | 61 ----- .../ServiceRegistrationTest.cs | 8 +- .../Xtensive.Orm.Tracking.Tests/TestHelper.cs | 4 +- .../TrackingItemTests.cs | 8 +- .../TrackingMonitorTests.cs | 8 +- .../TrackingStackFrameTests.cs | 171 ++++++------ .../TrackingTestBase.cs | 33 +++ .../Xtensive.Orm.Tracking.Tests.csproj | 4 +- .../Properties/Visibility.cs | 12 + .../Xtensive.Orm.Tracking.csproj | 3 - 45 files changed, 856 insertions(+), 1063 deletions(-) delete mode 100644 Extensions/TestCommon/DomainConfigurationFactory.cs delete mode 100644 Extensions/TestCommon/HasAccessToConfigurationTest.cs delete mode 100644 Extensions/TestCommon/TestConfiguration.cs rename Extensions/Xtensive.Orm.BulkOperations.Tests/{AutoBuildTest.cs => BulkOperationBaseTest.cs} (57%) rename Extensions/Xtensive.Orm.Localization.Tests/{AutoBuildTest.cs => LocalizationBaseTest.cs} (52%) delete mode 100644 Extensions/Xtensive.Orm.Reprocessing.Tests/AutoBuildTest.cs create mode 100644 Extensions/Xtensive.Orm.Reprocessing.Tests/ReprocessingBaseTest.cs delete mode 100644 Extensions/Xtensive.Orm.Security.Tests/AutoBuildTest.cs create mode 100644 Extensions/Xtensive.Orm.Security.Tests/SecurityTestBase.cs delete mode 100644 Extensions/Xtensive.Orm.Tracking.Tests/AutoBuildTest.cs create mode 100644 Extensions/Xtensive.Orm.Tracking.Tests/TrackingTestBase.cs create mode 100644 Extensions/Xtensive.Orm.Tracking/Properties/Visibility.cs diff --git a/Extensions/TestCommon/CommonModelTest.cs b/Extensions/TestCommon/CommonModelTest.cs index b0cc5a881c..fb917bb79c 100644 --- a/Extensions/TestCommon/CommonModelTest.cs +++ b/Extensions/TestCommon/CommonModelTest.cs @@ -1,68 +1,35 @@ // Copyright (C) 2019-2020 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. - -using System.Collections.Generic; using NUnit.Framework; using TestCommon.Model; -using Xtensive.Core; -using Xtensive.Orm; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Tests; namespace TestCommon { [TestFixture] - public abstract class CommonModelTest + public abstract class CommonModelTest : AutoBuildTest { - private List notDisposed; - - protected Domain Domain { get; private set; } + private bool justBuilt = true; [SetUp] public virtual void SetUp() { - CheckRequirements(); - var config = BuildConfiguration(); - Domain = BuildDomain(config); - notDisposed = new List(); - Domain.SessionOpen += (sender, args) => { - notDisposed.Add(args.Session); - args.Session.Events.Disposing += (o, eventArgs) => { - lock (notDisposed) { - notDisposed.Remove(args.Session); - } - }; - }; - PopulateData(); + if (justBuilt) { + justBuilt = false; + } + else { + RebuildDomain(); + } } - [TearDown] - public virtual void TearDown() - { - if (notDisposed!=null) - Assert.That(notDisposed, Is.Empty); - Assert.That(SessionScope.CurrentSession, Is.Null); - Domain.DisposeSafely(); - } - protected virtual DomainConfiguration BuildConfiguration() + protected override DomainConfiguration BuildConfiguration() { - var configuration = DomainConfigurationFactory.Create(); + var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof (Bar).Assembly); return configuration; } - - protected virtual Domain BuildDomain(DomainConfiguration configuration) - { - return Domain.Build(configuration); - } - - protected virtual void PopulateData() - { - } - - protected virtual void CheckRequirements() - { - } } } \ No newline at end of file diff --git a/Extensions/TestCommon/DomainConfigurationFactory.cs b/Extensions/TestCommon/DomainConfigurationFactory.cs deleted file mode 100644 index 66002c08ab..0000000000 --- a/Extensions/TestCommon/DomainConfigurationFactory.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Xtensive.Orm; -using Xtensive.Orm.Configuration; - -namespace TestCommon -{ - public static class DomainConfigurationFactory - { - public static DomainConfiguration Create(string name = null) - { - var testConfiguration = TestConfiguration.Instance; - var storageName = name ?? testConfiguration.Storage; - - var configuration = typeof(DomainConfigurationFactory).Assembly.GetAssemblyConfiguration(); - var domainConfiguration = DomainConfiguration.Load(configuration, storageName); - domainConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - var customConnectionInfo = testConfiguration.GetConnectionInfo(storageName); - if (customConnectionInfo != null) - domainConfiguration.ConnectionInfo = customConnectionInfo; - return domainConfiguration; - } - } -} \ No newline at end of file diff --git a/Extensions/TestCommon/HasAccessToConfigurationTest.cs b/Extensions/TestCommon/HasAccessToConfigurationTest.cs deleted file mode 100644 index 7b8b935f65..0000000000 --- a/Extensions/TestCommon/HasAccessToConfigurationTest.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NUnit.Framework; -using Xtensive.Orm.Configuration; - -namespace TestCommon -{ - [TestFixture] - public abstract class HasConfigurationAccessTest - { - public System.Configuration.Configuration Configuration - { - get { return GetConfigurationForTestAssembly(); } - } - - private System.Configuration.Configuration GetConfigurationForTestAssembly() - { - return GetType().Assembly.GetAssemblyConfiguration(); - } - } -} diff --git a/Extensions/TestCommon/TestConfiguration.cs b/Extensions/TestCommon/TestConfiguration.cs deleted file mode 100644 index 38369533e7..0000000000 --- a/Extensions/TestCommon/TestConfiguration.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Xtensive.Orm; - -namespace TestCommon -{ - public sealed class TestConfiguration - { - private const string StorageKey = "DO_STORAGE"; - private const string StorageFileKey = "DO_STORAGE_FILE"; - private const string ConfigurationFileKey = "DO_CONFIG_FILE"; - private const string DefaultStorage = "default"; - - private static readonly object InstanceLock = new object(); - private static TestConfiguration InstanceValue; - - private readonly Dictionary configuration; - - public static TestConfiguration Instance - { - get - { - lock (InstanceLock) { - if (InstanceValue==null) - InstanceValue = new TestConfiguration(); - return InstanceValue; - } - } - } - - public string Storage { get; private set; } - - public ConnectionInfo GetConnectionInfo(string name) - { - var value = GetConfigurationVariable(name); - if (value==null) - return null; - - if (!value.StartsWith("[")) - return new ConnectionInfo(value); - - var items = value.Split(new[] {'[', ']'}, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).ToArray(); - if (items.Length!=2) - throw new InvalidOperationException(string.Format("Invalid connection string format: {0}", value)); - return new ConnectionInfo(items[0], items[1]); - } - - private string GetEnvironmentVariable(string key) - { - return new[] {EnvironmentVariableTarget.Process, EnvironmentVariableTarget.User, EnvironmentVariableTarget.Machine} - .Select(target => Environment.GetEnvironmentVariable(key, target)) - .FirstOrDefault(result => !string.IsNullOrEmpty(result)); - } - - private string GetConfigurationVariable(string key) - { - string result; - if (configuration.TryGetValue(key, out result) && !string.IsNullOrEmpty(result)) - return result; - return null; - } - - private static Dictionary ParseConfigurationFile(string file) - { - var entries = - from line in File.ReadAllLines(file) - let items = line.Trim().Split(new[] {'='}, 2) - where items.Length==2 - let key = items[0].Trim() - let value = items[1].Trim() - where key!=string.Empty && value!=string.Empty - select new {key, value}; - return entries.ToDictionary(i => i.key, i => i.value); - } - - private Dictionary LoadConfiguration() - { - var configurationFile = GetEnvironmentVariable(ConfigurationFileKey); - if (configurationFile!=null && File.Exists(configurationFile)) - return ParseConfigurationFile(configurationFile); - return new Dictionary(); - } - - private string GetStorageFromFile() - { - var storageFile = GetEnvironmentVariable(StorageFileKey); - if (storageFile!=null && File.Exists(storageFile)) - return File.ReadAllLines(storageFile).Select(l => l.Trim()).FirstOrDefault(l => !string.IsNullOrEmpty(l)); - return null; - } - - private TestConfiguration() - { - configuration = LoadConfiguration(); - Storage = GetEnvironmentVariable(StorageKey) ?? GetStorageFromFile() ?? DefaultStorage; - } - } -} diff --git a/Extensions/TestCommon/Tests/TestConfigurationTest.cs b/Extensions/TestCommon/Tests/TestConfigurationTest.cs index 7c25adc63c..d6eb9f01f5 100644 --- a/Extensions/TestCommon/Tests/TestConfigurationTest.cs +++ b/Extensions/TestCommon/Tests/TestConfigurationTest.cs @@ -1,5 +1,6 @@ -using System; +using System; using NUnit.Framework; +using Xtensive.Orm.Tests; namespace TestCommon.Tests { diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/AutoBuildTest.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/BulkOperationBaseTest.cs similarity index 57% rename from Extensions/Xtensive.Orm.BulkOperations.Tests/AutoBuildTest.cs rename to Extensions/Xtensive.Orm.BulkOperations.Tests/BulkOperationBaseTest.cs index 09c6d280c3..08db8d6b8b 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/AutoBuildTest.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/BulkOperationBaseTest.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using TestCommon; using TestCommon.Model; using Xtensive.Orm.Configuration; @@ -6,13 +6,13 @@ namespace Xtensive.Orm.BulkOperations.Tests { [TestFixture] - public abstract class AutoBuildTest : CommonModelTest + public abstract class BulkOperationBaseTest : CommonModelTest { protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (IUpdatable<>).Assembly); - configuration.Types.Register(typeof (AutoBuildTest).Assembly); + configuration.Types.Register(typeof(IUpdatable<>).Assembly); + configuration.Types.Register(typeof(BulkOperationBaseTest).Assembly); return configuration; } } diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/ContainsTest.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/ContainsTest.cs index eed53dd38f..846f628e59 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/ContainsTest.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/ContainsTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2020 Xtensive LLC. +// Copyright (C) 2020-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -29,7 +29,7 @@ public TagType(Session session, long id) namespace Xtensive.Orm.BulkOperations.Tests { - public class ContainsTest : AutoBuildTest + public class ContainsTest : BulkOperationBaseTest { private long[] tagIds; @@ -45,8 +45,10 @@ protected override void PopulateData() tagIds = Enumerable.Range(0, 100).Select(i => (long) i).ToArray(); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - foreach (var id in tagIds.Concat(Enumerable.Repeat(1000, 1).Select(i => (long) i))) - new TagType(session, id) { ProjectedValueAdjustment = -1 }; + foreach (var id in tagIds.Concat(Enumerable.Repeat(1000, 1).Select(i => (long) i))) { + _ = new TagType(session, id) { ProjectedValueAdjustment = -1 }; + } + transaction.Complete(); } } @@ -86,7 +88,7 @@ public void Test3() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - Assert.Throws(() => session.Query.All() + _ = Assert.Throws(() => session.Query.All() .Where(t => t.Id.In(IncludeAlgorithm.TemporaryTable, tagIds)) .Set(t => t.ProjectedValueAdjustment, 2) .Update()); diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/Extensions.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/Extensions.cs index 7f10d10e70..12e0346781 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/Extensions.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/Extensions.cs @@ -8,7 +8,7 @@ public static class Extensions { public static void AssertCommandCount(this Session session, IResolveConstraint expression, Action action) { - int count = 0; + var count = 0; session.Events.DbCommandExecuting += (sender, args) => count++; action(); Assert.That(count, expression); diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0560_ChangeFieldWhichDefinedInAncestorClassBug.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0560_ChangeFieldWhichDefinedInAncestorClassBug.cs index e6b2923ec8..62deb808ab 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0560_ChangeFieldWhichDefinedInAncestorClassBug.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0560_ChangeFieldWhichDefinedInAncestorClassBug.cs @@ -44,19 +44,19 @@ public abstract class AbstractBaseForServiceMaterial : Entity namespace Xtensive.Orm.BulkOperations.Tests.Issues { - public class IssueJira0560_ChangeFieldWhichDefinedInAncestorClassBug : AutoBuildTest + public class IssueJira0560_ChangeFieldWhichDefinedInAncestorClassBug : BulkOperationBaseTest { [Test] public void UpdateTest() { - List keys = new List(); + var keys = new List(); using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - for (int i = 0; i < 10; i++) { + for (var i = 0; i < 10; i++) { var owner = new PreservedService(); keys.Add(owner.Id); - new ServiceMaterial { Active = false, Owner = owner }; + _ = new ServiceMaterial { Active = false, Owner = owner }; } transaction.Complete(); } diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0565_IgnoringTakeMethodOnTranslation.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0565_IgnoringTakeMethodOnTranslation.cs index 57e60ab38c..5178aefa4c 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0565_IgnoringTakeMethodOnTranslation.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/IssueJira0565_IgnoringTakeMethodOnTranslation.cs @@ -9,10 +9,11 @@ using NUnit.Framework; using TestCommon.Model; using Xtensive.Orm.Providers; +using Xtensive.Orm.Tests; namespace Xtensive.Orm.BulkOperations.Tests.Issues { - public class IssueJira0565_IgnoringTakeMethodOnTranslation : AutoBuildTest + public class IssueJira0565_IgnoringTakeMethodOnTranslation : BulkOperationBaseTest { [Test] public void UpdateOperationWithoutLimitation01() @@ -24,7 +25,7 @@ public void UpdateOperationWithoutLimitation01() var expectedUpdatedCount = baseQuery.Count(); var updatedCount = baseQuery.Set(el => el.Description, "UpdatedAgain").Update(); Assert.That(updatedCount, Is.EqualTo(expectedUpdatedCount)); - var updatedList = baseQuery.Where(el => el.Description=="UpdatedAgain").ToList(); + var updatedList = baseQuery.Where(el => el.Description == "UpdatedAgain").ToList(); Assert.That(updatedList.Count, Is.EqualTo(expectedUpdatedCount)); } } @@ -39,7 +40,7 @@ public void UpdateOperationWithoutLimitation02() var expectedUpdatedCount = baseQuery.Count(); var updatedCount = baseQuery.Set(el => el.Description, "UpdatedAgain").Update(); Assert.That(updatedCount, Is.EqualTo(expectedUpdatedCount)); - var updatedList = session.Query.All().Where(el => el.Description=="UpdatedAgain").ToList(); + var updatedList = session.Query.All().Where(el => el.Description == "UpdatedAgain").ToList(); Assert.That(updatedList.Count, Is.EqualTo(expectedUpdatedCount)); } } @@ -65,7 +66,8 @@ public void DeleteOperationWithoutLimitation02() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - var baseQuery = session.Query.All().Where(el => el.Id < 51).Union(session.Query.All().Where(el => el.Id > 200)); + var baseQuery = session.Query.All().Where(el => el.Id < 51) + .Union(session.Query.All().Where(el => el.Id > 200)); var expectedDeletedCount = baseQuery.Count(); var deletedCount = baseQuery.Delete(); Assert.That(deletedCount, Is.EqualTo(expectedDeletedCount)); @@ -83,7 +85,7 @@ public void UpdateOperationWithLimitation01() var expectedUpdatedCount = baseQuery.Count(); var updatedCount = baseQuery.Set(el => el.Description, "UpdatedAgain").Update(); Assert.That(updatedCount, Is.EqualTo(expectedUpdatedCount)); - var updatedList = session.Query.All().Where(el => el.Description=="UpdatedAgain").ToList(); + var updatedList = session.Query.All().Where(el => el.Description == "UpdatedAgain").ToList(); Assert.That(updatedList.Count, Is.EqualTo(expectedUpdatedCount)); } } @@ -95,11 +97,12 @@ public void UpdateOperationWithLimitation02() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - var baseQuery = session.Query.All().Where(el => el.Id < 100).Take(50).Union(session.Query.All().Where(el => el.Id > 100).Take(50)); + var baseQuery = session.Query.All().Where(el => el.Id < 100).Take(50) + .Union(session.Query.All().Where(el => el.Id > 100).Take(50)); var expectedUpdatedCount = baseQuery.Count(); var updatedCount = baseQuery.Set(el => el.Description, "UpdatedAgain").Update(); Assert.That(updatedCount, Is.EqualTo(expectedUpdatedCount)); - var updatedList = session.Query.All().Where(el => el.Description=="UpdatedAgain").ToList(); + var updatedList = session.Query.All().Where(el => el.Description == "UpdatedAgain").ToList(); Assert.That(updatedCount, Is.EqualTo(expectedUpdatedCount)); } } @@ -111,11 +114,12 @@ public void UpdateOperationWithLimitation03() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - var baseQuery = session.Query.All().Where(el => el.Id < 100).Union(session.Query.All().Where(el => el.Id > 100)).Take(100); + var baseQuery = session.Query.All().Where(el => el.Id < 100) + .Union(session.Query.All().Where(el => el.Id > 100)).Take(100); var expectedUpdatedCount = baseQuery.Count(); var updated = baseQuery.Set(el => el.Description, "UpdatedAgain").Update(); Assert.That(updated, Is.EqualTo(expectedUpdatedCount)); - var updatedList = session.Query.All().Where(el => el.Description=="UpdatedAgain").ToList(); + var updatedList = session.Query.All().Where(el => el.Description == "UpdatedAgain").ToList(); Assert.That(updatedList.Count, Is.EqualTo(100)); } } @@ -127,7 +131,8 @@ public void UpdateOperationWithLimitation04() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()){ - Assert.Throws(()=>session.Query.All().Take(200).Set(el => el.Description, "UpdatedAgain").Update()); + _ = Assert.Throws( + () =>session.Query.All().Take(200).Set(el => el.Description, "UpdatedAgain").Update()); } } @@ -138,8 +143,8 @@ public void UpdateOperationWithLimitation05() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( - ()=>session.Query.All().Where(el => el.Id < 100) + _ = Assert.Throws( + () => session.Query.All().Where(el => el.Id < 100) .Union(session.Query.All().Where(el => el.Id > 100)) .Take(100) .Set(el => el.Description, "UpdatedAgain") @@ -166,12 +171,15 @@ public void DeleteOperationWithLimitation01() public void DeleteOperationWithLimitation02() { SupportsDeleteLimitation(); - if(StringComparer.InvariantCultureIgnoreCase.Compare(Domain.StorageProviderInfo.ProviderName, WellKnown.Provider.Firebird)==0) - IgnoreMe("Ignored due to FireBird ignores Take X in delete statement", null); + Require.ProviderIsNot(StorageProvider.Firebird, "FireBird ignores Take X in delete statement"); + using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - var baseQuery = session.Query.All().Where(el => el.Id < 100).Take(50).Union(session.Query.All().Where(el => el.Id > 100).Take(50)); + var baseQuery = session.Query.All() + .Where(el => el.Id < 100) + .Take(50) + .Union(session.Query.All().Where(el => el.Id > 100).Take(50)); var expectedDeletedCount = baseQuery.Count(); var updatedCount = baseQuery.Delete(); Assert.That(updatedCount, Is.EqualTo(expectedDeletedCount)); @@ -185,7 +193,10 @@ public void DeleteOperationWithLimitation03() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - var baseQuery = session.Query.All().Where(el => el.Id < 100).Union(session.Query.All().Where(el => el.Id > 100)).Take(100); + var baseQuery = session.Query.All() + .Where(el => el.Id < 100) + .Union(session.Query.All().Where(el => el.Id > 100)) + .Take(100); var expectedDeletedCount = baseQuery.Count(); var updated = baseQuery.Delete(); Assert.That(updated, Is.EqualTo(expectedDeletedCount)); @@ -199,7 +210,7 @@ public void DeleteOperationWithLimitation04() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(()=>session.Query.All().Take(100).Delete()); + _ = Assert.Throws(()=>session.Query.All().Take(100).Delete()); } } @@ -210,7 +221,13 @@ public void DeleteOperationWithLimitation05() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => session.Query.All().Where(el => el.Id < 100).Union(session.Query.All().Where(el => el.Id > 100)).Take(100).Delete()); + _ = Assert.Throws( + () => session.Query.All() + .Where(el => el.Id < 100) + .Union(session.Query.All().Where(el => el.Id > 100)) + .Take(100) + .Delete() + ); } } @@ -225,11 +242,11 @@ public void UpdateOperationTableAsSource() Assert.AreEqual(200, list.Count); var updated = session.Query.All().Take(200).Set(el => el.Description, "Updated").Update(); Assert.AreEqual(200, updated); - var updatedList = session.Query.All().Where(el => el.Description=="Updated").ToList(); + var updatedList = session.Query.All().Where(el => el.Description == "Updated").ToList(); Assert.AreEqual(200, updatedList.Count); updated = session.Query.All().Set(el => el.Description, "UpdatedAgain").Update(); Assert.AreEqual(250, updated); - updatedList = session.Query.All().Where(el => el.Description=="UpdatedAgain").ToList(); + updatedList = session.Query.All().Where(el => el.Description == "UpdatedAgain").ToList(); Assert.AreEqual(250, updatedList.Count); } } @@ -240,8 +257,8 @@ protected override void PopulateData() using (var session = Domain.OpenSession()) using (session.Activate()) using (var transaction = session.OpenTransaction()) { - for (int i = 0; i< 250; i++) { - new Bar(session); + for (var i = 0; i< 250; i++) { + _ = new Bar(session); } transaction.Complete(); } @@ -256,37 +273,43 @@ protected override Configuration.DomainConfiguration BuildConfiguration() private void SupportsUpdateLimitation() { - if (!Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateLimit) && - !Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateFrom)) + if (!Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateLimit) + && !Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateFrom)) { IgnoreMe("This provider does not support limitation of affecred rows on update.", null); + } } private void DoesNotSupportsUpdateLimitation() { - if (Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateLimit) || - Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateFrom)) + if (Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateLimit) + || Domain.StorageProviderInfo.Supports(ProviderFeatures.UpdateFrom)) { IgnoreMe("This provider supports update limitation", null); + } } private void SupportsDeleteLimitation() { - if (!Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteLimit) && - !Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteFrom)) + if (!Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteLimit) + && !Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteFrom)) { IgnoreMe("This provider does not support limitation of affecred rows on delet.", null); + } } private void DoesNotSupportsDeleteLimitation() { - if (Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteLimit) || - Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteFrom)) + if (Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteLimit) + || Domain.StorageProviderInfo.Supports(ProviderFeatures.DeleteFrom)) { IgnoreMe("This provider support delete limitation", null); + } } private static void IgnoreMe(string format, object argument, string reason = null) { var message = string.Format(format, argument); - if (!string.IsNullOrEmpty(reason)) + if (!string.IsNullOrEmpty(reason)) { message = string.Format("{0}. Reason: {1}", message, reason); + } + throw new IgnoreException(message); } } diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/JoinedTableAsSourceForDelete.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/JoinedTableAsSourceForDelete.cs index 9a08893b45..20218136e8 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/JoinedTableAsSourceForDelete.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/Issues/JoinedTableAsSourceForDelete.cs @@ -1,15 +1,10 @@ -using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using NUnit.Framework; -using TestCommon.Model; using Xtensive.Orm.BulkOperations.Tests.Issues.WrongAliassesIssue; -using Xtensive.Sql; namespace Xtensive.Orm.BulkOperations.Tests.Issues { - public class JoinedTableAsSourceForOperationsCauseWrongAliases : AutoBuildTest + public class JoinedTableAsSourceForOperationsCauseWrongAliases : BulkOperationBaseTest { [Test] public void CustomerCase() diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs index 98be7bf083..485a0d72d8 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/Other.cs @@ -13,7 +13,7 @@ namespace Xtensive.Orm.BulkOperations.Tests { - internal class Other : AutoBuildTest + internal class Other : BulkOperationBaseTest { [Test] public void CompositeKeyUpdate() @@ -46,9 +46,9 @@ public void SimpleDelete() var bar2 = new Bar(session); var bar3 = new Bar(session); _ = bar3.Foo.Add(new Foo(session) { Name = "Foo" }); - string s = "test"; + var s = "test"; - int deleted = session.Query.All().Where(a => a.Name == s).Delete(); + var deleted = session.Query.All().Where(a => a.Name == s).Delete(); Assert.That(bar1.IsRemoved, Is.True); Assert.That(bar2.IsRemoved, Is.False); Assert.That(bar3.IsRemoved, Is.False); diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs index 57e0a0b528..9e8d74df75 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/ReferenceFields.cs @@ -5,7 +5,7 @@ namespace Xtensive.Orm.BulkOperations.Tests { - internal class ReferenceFields : AutoBuildTest + internal class ReferenceFields : BulkOperationBaseTest { [Test] public void InsertClientSideReferenceField() diff --git a/Extensions/Xtensive.Orm.BulkOperations.Tests/Structures.cs b/Extensions/Xtensive.Orm.BulkOperations.Tests/Structures.cs index 49e211b07a..59aacb1b58 100644 --- a/Extensions/Xtensive.Orm.BulkOperations.Tests/Structures.cs +++ b/Extensions/Xtensive.Orm.BulkOperations.Tests/Structures.cs @@ -4,128 +4,151 @@ namespace Xtensive.Orm.BulkOperations.Tests { - internal class Structures : AutoBuildTest + internal class Structures : BulkOperationBaseTest { [Test] public void StructuresSet() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar(session) {Count = 5}; - - session.Query.All().Set(a => a.Rectangle, new Rectangle(session) {BorderWidth = 1}).Update(); - Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(1)); - - session.Query.All().Set(a => a.Rectangle, new Rectangle(session)).Update(); - Assert.That(bar.Rectangle.BorderWidth, Is.Null); - - session.Query.All().Set( - a => a.Rectangle, new Rectangle(session) {BorderWidth = 2, First = new Point(session) {X = 3, Y = 4}}).Update( - ); - Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(2)); - Assert.That(bar.Rectangle.First.X, Is.EqualTo(3)); - Assert.That(bar.Rectangle.First.Y, Is.EqualTo(4)); - Assert.That(bar.Rectangle.Second.X, Is.Null); - bar.Rectangle = new Rectangle(session); - - session.Query.All().Set(a => a.Rectangle.First.X, 1).Update(); - Assert.That(bar.Rectangle.First.X, Is.EqualTo(1)); - Assert.That(bar.Rectangle.Second.X, Is.Null); - bar.Rectangle = new Rectangle(session); - - /*var bar2 = new Bar(session); - session.SaveChanges(); - session.AssertCommandCount(Is.EqualTo(1), () => { - session.Query.All().Where(a => a.Id==bar2.Id).Set( - a => a.Rectangle, - a => session.Query.All().Where(b => a.Id==bar.Id).Select(b => b.Rectangle).First()). - Update(); - }); - Assert.That( bar2.Rectangle.First.X, Is.EqualTo(1)); - Assert.That(bar2.Rectangle.Second.X, Is.Null); - bar2.Remove();*/ - - session.Query.All().Set(a => a.Rectangle.BorderWidth, a => a.Count * 2).Update(); - Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(10)); - - bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; - session.Query.All().Set(a => a.Rectangle.BorderWidth, 1).Set( - a => a.Rectangle.First, a => new Point(session) {X = 2}).Update(); - Assert.That( - bar.Rectangle, - Is.EqualTo( - new Rectangle(session) { - BorderWidth = 1, - First = new Point(session) {X = 2, Y = 2}, - Second = new Point(session) {X = 3, Y = 4} - })); - bar.Rectangle = new Rectangle(session); - - bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; - session.Query.All().Set(a => a.Rectangle.BorderWidth, 1).Set( - a => a.Rectangle.First, new Point(session) {X = 2}).Update(); - Assert.That( - bar.Rectangle, - Is.EqualTo( - new Rectangle(session) { - BorderWidth = 1, - First = new Point(session) {X = 2, Y = null}, - Second = new Point(session) {X = 3, Y = 4} - })); - bar.Rectangle = new Rectangle(session); - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + var bar = new Bar(session) { Count = 5 }; + + _ = session.Query.All().Set(a => a.Rectangle, new Rectangle(session) { BorderWidth = 1 }).Update(); + Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(1)); + + _ = session.Query.All().Set(a => a.Rectangle, new Rectangle(session)).Update(); + Assert.That(bar.Rectangle.BorderWidth, Is.Null); + + _ = session.Query.All() + .Set(a => a.Rectangle, new Rectangle(session) { BorderWidth = 2, First = new Point(session) { X = 3, Y = 4 } }) + .Update(); + Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(2)); + Assert.That(bar.Rectangle.First.X, Is.EqualTo(3)); + Assert.That(bar.Rectangle.First.Y, Is.EqualTo(4)); + Assert.That(bar.Rectangle.Second.X, Is.Null); + bar.Rectangle = new Rectangle(session); + + _ = session.Query.All().Set(a => a.Rectangle.First.X, 1).Update(); + Assert.That(bar.Rectangle.First.X, Is.EqualTo(1)); + Assert.That(bar.Rectangle.Second.X, Is.Null); + bar.Rectangle = new Rectangle(session); + + /*var bar2 = new Bar(session); + session.SaveChanges(); + session.AssertCommandCount(Is.EqualTo(1), () => { + session.Query.All().Where(a => a.Id==bar2.Id).Set( + a => a.Rectangle, + a => session.Query.All().Where(b => a.Id==bar.Id).Select(b => b.Rectangle).First()). + Update(); + }); + Assert.That( bar2.Rectangle.First.X, Is.EqualTo(1)); + Assert.That(bar2.Rectangle.Second.X, Is.Null); + bar2.Remove();*/ + + _ = session.Query.All().Set(a => a.Rectangle.BorderWidth, a => a.Count * 2).Update(); + Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(10)); + + bar.Rectangle = new Rectangle(session) { + First = new Point(session) { X = 1, Y = 2 }, + Second = new Point(session) { X = 3, Y = 4 } + }; + _ = session.Query.All() + .Set(a => a.Rectangle.BorderWidth, 1) + .Set(a => a.Rectangle.First, a => new Point(session) { X = 2 }) + .Update(); + Assert.That( + bar.Rectangle, + Is.EqualTo( + new Rectangle(session) { + BorderWidth = 1, + First = new Point(session) { X = 2, Y = 2 }, + Second = new Point(session) { X = 3, Y = 4 } + })); + bar.Rectangle = new Rectangle(session); + + bar.Rectangle = new Rectangle(session) { + First = new Point(session) { X = 1, Y = 2 }, + Second = new Point(session) { X = 3, Y = 4 } + }; + _ = session.Query.All() + .Set(a => a.Rectangle.BorderWidth, 1) + .Set(a => a.Rectangle.First, new Point(session) { X = 2 }) + .Update(); + Assert.That( + bar.Rectangle, + Is.EqualTo( + new Rectangle(session) { + BorderWidth = 1, + First = new Point(session) { X = 2, Y = null }, + Second = new Point(session) { X = 3, Y = 4 } + })); + bar.Rectangle = new Rectangle(session); + trx.Complete(); } } [Test] public void StructuresUpdate() { - using (Session session = Domain.OpenSession()) { - using (TransactionScope trx = session.OpenTransaction()) { - var bar = new Bar(session) {Count = 5}; - - session.Query.All().Update( - a => new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = 1}}); - Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(1)); - - session.Query.All().Update(a => new Bar(null) {Rectangle = new Rectangle(session)}); - Assert.That(bar.Rectangle.BorderWidth, Is.Null); - - session.Query.All().Update( - a => - new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = 2, First = new Point(session) {X = 3, Y = 4}}}); - Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(2)); - Assert.That(bar.Rectangle.First.X, Is.EqualTo(3)); - Assert.That(bar.Rectangle.First.Y, Is.EqualTo(4)); - Assert.That(bar.Rectangle.Second.X, Is.Null); - bar.Rectangle = new Rectangle(session); - - session.Query.All().Update( - a => new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = a.Count * 2}}); - Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(10)); - bar.Rectangle = new Rectangle(session); - - bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; - session.Query.All().Update( - a => new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = 1, First = new Point(session) {X = 2}}}); - Assert.That( - bar.Rectangle, - Is.EqualTo( - new Rectangle(session) { - BorderWidth = 1, - First = new Point(session) {X = 2, Y = 2}, - Second = new Point(session) {X = 3, Y = 4} - })); - bar.Rectangle = new Rectangle(session); - - var rectangle = new Rectangle(session) {BorderWidth = 1, First = new Point(session) {X = 2}}; - bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; - session.Query.All().Update(a => new Bar(null) {Rectangle = rectangle}); - Assert.That(bar.Rectangle, Is.EqualTo(rectangle)); - bar.Rectangle = new Rectangle(session); - trx.Complete(); - } + using (Session session = Domain.OpenSession()) + using (TransactionScope trx = session.OpenTransaction()) { + var bar = new Bar(session) { Count = 5 }; + + _ = session.Query.All() + .Update(a => new Bar(null) { Rectangle = new Rectangle(session) { BorderWidth = 1 } }); + Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(1)); + + _ = session.Query.All() + .Update(a => new Bar(null) { Rectangle = new Rectangle(session) }); + Assert.That(bar.Rectangle.BorderWidth, Is.Null); + + _ = session.Query.All() + .Update(a => + new Bar(null) { Rectangle = new Rectangle(session) { BorderWidth = 2, First = new Point(session) { X = 3, Y = 4 } } } + ); + Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(2)); + Assert.That(bar.Rectangle.First.X, Is.EqualTo(3)); + Assert.That(bar.Rectangle.First.Y, Is.EqualTo(4)); + Assert.That(bar.Rectangle.Second.X, Is.Null); + bar.Rectangle = new Rectangle(session); + + _ = session.Query.All() + .Update(a => + new Bar(null) { Rectangle = new Rectangle(session) { BorderWidth = a.Count * 2 } } + ); + Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(10)); + bar.Rectangle = new Rectangle(session); + + bar.Rectangle = new Rectangle(session) { + First = new Point(session) { X = 1, Y = 2 }, + Second = new Point(session) { X = 3, Y = 4 } + }; + _ = session.Query.All() + .Update(a => + new Bar(null) { Rectangle = new Rectangle(session) { BorderWidth = 1, First = new Point(session) { X = 2 } } } + ); + Assert.That( + bar.Rectangle, + Is.EqualTo( + new Rectangle(session) { + BorderWidth = 1, + First = new Point(session) { X = 2, Y = 2 }, + Second = new Point(session) { X = 3, Y = 4 } + })); + bar.Rectangle = new Rectangle(session); + + var rectangle = new Rectangle(session) { + BorderWidth = 1, + First = new Point(session) { X = 2 } + }; + bar.Rectangle = new Rectangle(session) { + First = new Point(session) { X = 1, Y = 2 }, + Second = new Point(session) { X = 3, Y = 4 } }; + + _ = session.Query.All().Update(a => new Bar(null) { Rectangle = rectangle }); + Assert.That(bar.Rectangle, Is.EqualTo(rectangle)); + bar.Rectangle = new Rectangle(session); + trx.Complete(); } } } diff --git a/Extensions/Xtensive.Orm.Localization.Tests/AccessToLocalizationOnUpgrade.cs b/Extensions/Xtensive.Orm.Localization.Tests/AccessToLocalizationOnUpgrade.cs index 353ae0b46a..708d7d83f3 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/AccessToLocalizationOnUpgrade.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/AccessToLocalizationOnUpgrade.cs @@ -1,13 +1,10 @@ -using System; -using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text; using NUnit.Framework; -using TestCommon; using Xtensive.Orm.Localization.Tests.Model; using Xtensive.Orm.Upgrade; using Xtensive.Orm.Localization.Tests.Model.Upgrader; +using Xtensive.Orm.Tests; namespace Xtensive.Orm.Localization.Tests.Model.Upgrader { @@ -20,7 +17,7 @@ public override bool CanUpgradeFrom(string oldVersion) public override void OnUpgrade() { - Query.All().FirstOrDefault(x => x.Title=="Welcome!"); + _ = Query.All().FirstOrDefault(x => x.Title == "Welcome!"); } } } @@ -42,8 +39,8 @@ public class AccessToLocalizationOnUpgrade public void TestFixtureSetup() { var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (ILocalizable<>).Assembly); - configuration.Types.Register(typeof (AutoBuildTest).Assembly, typeof (AutoBuildTest).Namespace); + configuration.Types.Register(typeof(ILocalizable<>).Assembly); + configuration.Types.Register(typeof(LocalizationBaseTest).Assembly, typeof(LocalizationBaseTest).Namespace); using (var domain = Domain.Build(configuration)) using (var session = domain.OpenSession()) @@ -64,14 +61,14 @@ public void MainTest() { var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(typeof (ILocalizable<>).Assembly); - configuration.Types.Register(typeof (AutoBuildTest).Assembly, typeof (AutoBuildTest).Namespace); + configuration.Types.Register(typeof (LocalizationBaseTest).Assembly, typeof (LocalizationBaseTest).Namespace); configuration.Types.Register(typeof (CustomUpgradeHandler)); configuration.UpgradeMode = DomainUpgradeMode.PerformSafely; using (var domain = Domain.Build(configuration)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All().FirstOrDefault(x => x.Title==EnglishTitle); + _ = session.Query.All().FirstOrDefault(x => x.Title==EnglishTitle); } } } diff --git a/Extensions/Xtensive.Orm.Localization.Tests/CurrentThreadTest.cs b/Extensions/Xtensive.Orm.Localization.Tests/CurrentThreadTest.cs index 0f149dd287..40ceb291dd 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/CurrentThreadTest.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/CurrentThreadTest.cs @@ -5,7 +5,7 @@ namespace Xtensive.Orm.Localization.Tests { - public class CurrentThreadTest : AutoBuildTest + public class CurrentThreadTest : LocalizationBaseTest { [Test] public void MainTest() diff --git a/Extensions/Xtensive.Orm.Localization.Tests/DirectEditTest.cs b/Extensions/Xtensive.Orm.Localization.Tests/DirectEditTest.cs index 0e22a72e4f..a3a4415841 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/DirectEditTest.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/DirectEditTest.cs @@ -4,43 +4,42 @@ namespace Xtensive.Orm.Localization.Tests { - public class DirectEditTest : AutoBuildTest + public class DirectEditTest : LocalizationBaseTest { [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - var welcomePage = new Page(session); + var welcomePage = new Page(session); - // Editing localizations directly - welcomePage.Localizations[EnglishCulture].Title = EnglishTitle; - welcomePage.Localizations[EnglishCulture].Content = EnglishContent; - welcomePage.Localizations[SpanishCulture].Title = SpanishTitle; - welcomePage.Localizations[SpanishCulture].Content = SpanishContent; + // Editing localizations directly + welcomePage.Localizations[EnglishCulture].Title = EnglishTitle; + welcomePage.Localizations[EnglishCulture].Content = EnglishContent; + welcomePage.Localizations[SpanishCulture].Title = SpanishTitle; + welcomePage.Localizations[SpanishCulture].Content = SpanishContent; - ts.Complete(); - } + ts.Complete(); } // Checking the presence of localizable & localization entities - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - Assert.AreEqual(1, session.Query.All().Count()); - Assert.AreEqual(2, session.Query.All().Count()); + Assert.AreEqual(1, session.Query.All().Count()); + Assert.AreEqual(2, session.Query.All().Count()); - var page = session.Query.All().First(); - Assert.AreEqual(EnglishTitle, page.Localizations[EnglishCulture].Title); - Assert.AreEqual(EnglishContent, page.Localizations[EnglishCulture].Content); + var page = session.Query.All().First(); + Assert.AreEqual(EnglishTitle, page.Localizations[EnglishCulture].Title); + Assert.AreEqual(EnglishContent, page.Localizations[EnglishCulture].Content); - Assert.AreEqual(SpanishTitle, page.Localizations[SpanishCulture].Title); - Assert.AreEqual(SpanishContent, page.Localizations[SpanishCulture].Content); + Assert.AreEqual(SpanishTitle, page.Localizations[SpanishCulture].Title); + Assert.AreEqual(SpanishContent, page.Localizations[SpanishCulture].Content); - ts.Complete(); - } + ts.Complete(); } + } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Localization.Tests/AutoBuildTest.cs b/Extensions/Xtensive.Orm.Localization.Tests/LocalizationBaseTest.cs similarity index 52% rename from Extensions/Xtensive.Orm.Localization.Tests/AutoBuildTest.cs rename to Extensions/Xtensive.Orm.Localization.Tests/LocalizationBaseTest.cs index 0e5d338e21..f8bed03f22 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/AutoBuildTest.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/LocalizationBaseTest.cs @@ -1,11 +1,12 @@ using System.Globalization; using NUnit.Framework; -using TestCommon; +using Xtensive.Orm.Configuration; +using Xtensive.Orm.Tests; namespace Xtensive.Orm.Localization.Tests { [TestFixture] - public abstract class AutoBuildTest + public abstract class LocalizationBaseTest : AutoBuildTest { public static CultureInfo EnglishCulture = new CultureInfo("en-US"); public static string EnglishTitle = "Welcome!"; @@ -15,20 +16,12 @@ public abstract class AutoBuildTest public static string SpanishTitle = "Bienvenido!"; public static string SpanishContent = "Mis amigos mejores! Bienvenido a mi cumpleanos!"; - protected Domain Domain { get; private set; } - - [OneTimeSetUp] - public void OneTimeSetUp() - { - var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (ILocalizable<>).Assembly); - configuration.Types.Register(typeof (AutoBuildTest).Assembly, typeof (AutoBuildTest).Namespace); - Domain = Domain.Build(configuration); - PopulateDatabase(); - } - - protected virtual void PopulateDatabase() + protected override DomainConfiguration BuildConfiguration() { + var configuration = base.BuildConfiguration(); + configuration.Types.Register(typeof(ILocalizable<>).Assembly); + configuration.Types.Register(typeof(LocalizationBaseTest).Assembly, typeof(LocalizationBaseTest).Namespace); + return configuration; } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Localization.Tests/LocalizationScopeTest.cs b/Extensions/Xtensive.Orm.Localization.Tests/LocalizationScopeTest.cs index dd59707afa..de7d6793e0 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/LocalizationScopeTest.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/LocalizationScopeTest.cs @@ -4,52 +4,50 @@ namespace Xtensive.Orm.Localization.Tests { - public class LocalizationScopeTest : AutoBuildTest + public class LocalizationScopeTest : LocalizationBaseTest { [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - var welcomePage = new Page(session); + var welcomePage = new Page(session); - // Editing localizable properties through localization scope - using (new LocalizationScope(EnglishCulture)) { - welcomePage.Title = EnglishTitle; - welcomePage.Content = EnglishContent; - } - - // The same entity, the same properties, but another culture - using (new LocalizationScope(SpanishCulture)) { - welcomePage.Title = SpanishTitle; - welcomePage.Content = SpanishContent; - } + // Editing localizable properties through localization scope + using (new LocalizationScope(EnglishCulture)) { + welcomePage.Title = EnglishTitle; + welcomePage.Content = EnglishContent; + } - ts.Complete(); + // The same entity, the same properties, but another culture + using (new LocalizationScope(SpanishCulture)) { + welcomePage.Title = SpanishTitle; + welcomePage.Content = SpanishContent; } + + ts.Complete(); } // Checking the presence of localizable & localization entities - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - Assert.AreEqual(1, session.Query.All().Count()); - Assert.AreEqual(2, session.Query.All().Count()); + Assert.AreEqual(1, session.Query.All().Count()); + Assert.AreEqual(2, session.Query.All().Count()); - var page = session.Query.All().First(); - using (new LocalizationScope(EnglishCulture)) { - Assert.AreEqual(EnglishTitle, page.Title); - Assert.AreEqual(EnglishContent, page.Content); - } - - using (new LocalizationScope(SpanishCulture)) { - Assert.AreEqual(SpanishTitle, page.Title); - Assert.AreEqual(SpanishContent, page.Content); - } + var page = session.Query.All().First(); + using (new LocalizationScope(EnglishCulture)) { + Assert.AreEqual(EnglishTitle, page.Title); + Assert.AreEqual(EnglishContent, page.Content); + } - ts.Complete(); + using (new LocalizationScope(SpanishCulture)) { + Assert.AreEqual(SpanishTitle, page.Title); + Assert.AreEqual(SpanishContent, page.Content); } + + ts.Complete(); } } } diff --git a/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs b/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs index f21be4054c..b6c774f609 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2009.11.27 diff --git a/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs b/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs index 271ec03e0c..a4c51e3c13 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2009.11.27 diff --git a/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs b/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs index 94848d3175..ed999a177f 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2019-2020 Xtensive LLC. +// Copyright (C) 2019-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -51,7 +51,7 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(ILocalizable<>).Assembly); - configuration.Types.Register(typeof(AutoBuildTest).Assembly, typeof(AutoBuildTest).Namespace); + configuration.Types.Register(typeof(LocalizationBaseTest).Assembly, typeof(LocalizationBaseTest).Namespace); configuration.DefaultSchema = DefaultNodeSchema; configuration.UpgradeMode = DomainUpgradeMode.Recreate; return configuration; diff --git a/Extensions/Xtensive.Orm.Localization.Tests/QueryTests.cs b/Extensions/Xtensive.Orm.Localization.Tests/QueryTests.cs index 8a3f6ee4ef..e298ff92a5 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/QueryTests.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/QueryTests.cs @@ -7,22 +7,21 @@ namespace Xtensive.Orm.Localization.Tests { [TestFixture] - public class QueryTests : AutoBuildTest + public class QueryTests : LocalizationBaseTest { - protected override void PopulateDatabase() + protected override void PopulateData() { - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - // populating database - var welcomePage = new Page(session); - welcomePage.Localizations[EnglishCulture].Title = EnglishTitle; - welcomePage.Localizations[EnglishCulture].Content = EnglishContent; - welcomePage.Localizations[SpanishCulture].Title = SpanishTitle; - welcomePage.Localizations[SpanishCulture].Content = SpanishContent; + // populating database + var welcomePage = new Page(session); + welcomePage.Localizations[EnglishCulture].Title = EnglishTitle; + welcomePage.Localizations[EnglishCulture].Content = EnglishContent; + welcomePage.Localizations[SpanishCulture].Title = SpanishTitle; + welcomePage.Localizations[SpanishCulture].Content = SpanishContent; - ts.Complete(); - } + ts.Complete(); } } @@ -35,7 +34,7 @@ public void ImplicitJoinViaPreprocessorTest() string title = EnglishTitle; var query = from p in session.Query.All() - where p.Title==title + where p.Title == title select p; Assert.AreEqual(1, query.Count()); @@ -48,20 +47,19 @@ public void ImplicitJoinViaPreprocessorTest() public void ExplicitJoinTest() { Thread.CurrentThread.CurrentCulture = EnglishCulture; - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - using (new LocalizationScope(SpanishCulture)) { - var query = from p in session.Query.All() - join pl in session.Query.All() - on p equals pl.Target - where pl.CultureName == LocalizationContext.Current.CultureName && pl.Title == SpanishTitle - select p; - Assert.AreEqual(1, query.Count()); - } - - ts.Complete(); + using (new LocalizationScope(SpanishCulture)) { + var query = from p in session.Query.All() + join pl in session.Query.All() + on p equals pl.Target + where pl.CultureName == LocalizationContext.Current.CultureName && pl.Title == SpanishTitle + select p; + Assert.AreEqual(1, query.Count()); } + + ts.Complete(); } } @@ -69,16 +67,15 @@ on p equals pl.Target public void QueryForLocalizationPairTest() { Thread.CurrentThread.CurrentCulture = EnglishCulture; - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - var pairs = from pair in session.Query.All() - where pair.Localization.Title==EnglishTitle - select pair.Target; - Assert.AreEqual(1, pairs.Count()); + var pairs = from pair in session.Query.All() + where pair.Localization.Title == EnglishTitle + select pair.Target; + Assert.AreEqual(1, pairs.Count()); - ts.Complete(); - } + ts.Complete(); } } @@ -86,16 +83,15 @@ public void QueryForLocalizationPairTest() public void UnknownCultureTest() { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("ru-RU"); - using (var session = Domain.OpenSession()) { - using (var ts = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var ts = session.OpenTransaction()) { - var query = from p in session.Query.All() - select p.Title; - Console.Write(query.First()); - Assert.AreEqual(1, query.Count()); + var query = from p in session.Query.All() + select p.Title; + Console.Write(query.First()); + Assert.AreEqual(1, query.Count()); - ts.Complete(); - } + ts.Complete(); } } } diff --git a/Extensions/Xtensive.Orm.Reprocessing.Tests/AutoBuildTest.cs b/Extensions/Xtensive.Orm.Reprocessing.Tests/AutoBuildTest.cs deleted file mode 100644 index aff8998f43..0000000000 --- a/Extensions/Xtensive.Orm.Reprocessing.Tests/AutoBuildTest.cs +++ /dev/null @@ -1,28 +0,0 @@ -using NUnit.Framework; -using TestCommon; -using TestCommon.Model; -using Xtensive.Orm.Configuration; -using Xtensive.Orm.Providers; - -namespace Xtensive.Orm.Reprocessing.Tests -{ - [TestFixture] - public abstract class AutoBuildTest : CommonModelTest - { - protected override DomainConfiguration BuildConfiguration() - { - var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (IExecuteActionStrategy).Assembly); - configuration.Types.Register(typeof (AutoBuildTest).Assembly); - return configuration; - } - - protected override Domain BuildDomain(DomainConfiguration configuration) - { - var domain = base.BuildDomain(configuration); - if (domain.StorageProviderInfo.Supports(ProviderFeatures.ExclusiveWriterConnection)) - Assert.Ignore("This storage does not support multiple sessions writing to the same database, ignoring"); - return domain; - } - } -} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Reprocessing.Tests/Extensions.cs b/Extensions/Xtensive.Orm.Reprocessing.Tests/Extensions.cs index 3884d22a81..40b41b0be9 100644 --- a/Extensions/Xtensive.Orm.Reprocessing.Tests/Extensions.cs +++ b/Extensions/Xtensive.Orm.Reprocessing.Tests/Extensions.cs @@ -1,20 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Data.Common; -using System.Linq; -using System.Text; using Xtensive.Core; using Xtensive.Orm; using Xtensive.Orm.Services; namespace TestCommon.Model { - static class Extensions + internal static class Extensions { public static void EnsureTransactionIsStarted(this Session session) { var accessor = session.Services.Demand(); - DbTransaction notUsed = accessor.Transaction; +#pragma warning disable IDE0059 // Unnecessary assignment of a value + var notUsed = accessor.Transaction; +#pragma warning restore IDE0059 // Unnecessary assignment of a value } } } diff --git a/Extensions/Xtensive.Orm.Reprocessing.Tests/ReprocessingBaseTest.cs b/Extensions/Xtensive.Orm.Reprocessing.Tests/ReprocessingBaseTest.cs new file mode 100644 index 0000000000..6871137be7 --- /dev/null +++ b/Extensions/Xtensive.Orm.Reprocessing.Tests/ReprocessingBaseTest.cs @@ -0,0 +1,27 @@ +using NUnit.Framework; +using TestCommon; +using TestCommon.Model; +using Xtensive.Orm.Configuration; +using Xtensive.Orm.Providers; +using Xtensive.Orm.Tests; + +namespace Xtensive.Orm.Reprocessing.Tests +{ + [TestFixture] + public abstract class ReprocessingBaseTest : CommonModelTest + { + protected override void CheckRequirements() + { + base.CheckRequirements(); + Require.AllFeaturesNotSupported(ProviderFeatures.ExclusiveWriterConnection); + } + + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.Types.Register(typeof(IExecuteActionStrategy).Assembly); + configuration.Types.Register(typeof(ReprocessingBaseTest).Assembly); + return configuration; + } + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Other.cs b/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Other.cs index a366a83623..1bb275cc20 100644 --- a/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Other.cs +++ b/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Other.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Transactions; using NUnit.Framework; using TestCommon.Model; @@ -7,16 +7,13 @@ namespace Xtensive.Orm.Reprocessing.Tests { - public class Other : AutoBuildTest + public class Other : ReprocessingBaseTest { private class TestExecuteStrategy : HandleUniqueConstraintViolationStrategy { #region Non-public methods - protected override bool OnError(ExecuteErrorEventArgs context) - { - return context.Attempt < 2; - } + protected override bool OnError(ExecuteErrorEventArgs context) => context.Attempt < 2; #endregion } @@ -24,16 +21,17 @@ protected override bool OnError(ExecuteErrorEventArgs context) [Test] public void ExecuteStrategy() { - int i = 0; + var i = 0; try { - ReprocessingConfiguration config = Domain.GetReprocessingConfiguration(); + var config = Domain.GetReprocessingConfiguration(); config.DefaultExecuteStrategy = typeof (TestExecuteStrategy); Domain.Execute( session => { - new Foo(session) {Name = "test"}; + _ = new Foo(session) {Name = "test"}; i++; - if (i < 5) - new Foo(session) {Name = "test"}; + if (i < 5) { + _ = new Foo(session) {Name = "test"}; + } }); } catch { @@ -55,19 +53,21 @@ public void NestedNewSession() [Test] public void NestedSessionReuse() { - Domain.Execute(session1 => Domain.Execute(session2 => Assert.That(session1, Is.SameAs(session2)))); + Domain.Execute( + session1 => Domain.Execute( + session2 => Assert.That(session1, Is.SameAs(session2)))); } [Test] public void Test() { Domain.Execute(session => { - new Foo(session); + _ = new Foo(session); }); Domain.Execute(session => { - session.Query.All().ToArray(); + _ = session.Query.All().ToArray(); Domain.WithIsolationLevel(IsolationLevel.Serializable).Execute(session2 => { - session2.Query.All().ToArray(); + _ = session2.Query.All().ToArray(); }); }); } @@ -75,21 +75,16 @@ public void Test() [Test] public void ParentIsDisconnectedState() { - Domain.Execute(session => - { - new Bar(session); - }); + Domain.Execute(session => { _ = new Bar(session); }); using (var session = Domain.OpenSession(new SessionConfiguration(SessionOptions.ClientProfile))) - using(session.Activate()) - { + using(session.Activate()) { var bar = session.Query.All().FirstOrDefault(); bar=new Bar(session); session.SaveChanges(); - Domain.Execute(session1 => - { - bar = session1.Query.All().FirstOrDefault(); - bar=new Bar(session1); - }); + Domain.Execute(session1 => { + bar = session1.Query.All().FirstOrDefault(); + bar = new Bar(session1); + }); session.SaveChanges(); } Domain.Execute(session => Assert.That(session.Query.All().Count(), Is.EqualTo(3))); diff --git a/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs b/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs index ba7741bb5e..11fe16b7fe 100644 --- a/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs +++ b/Extensions/Xtensive.Orm.Reprocessing.Tests/Tests/Reprocessing.cs @@ -12,7 +12,7 @@ namespace Xtensive.Orm.Reprocessing.Tests { - public class Reprocessing : AutoBuildTest + public class Reprocessing : ReprocessingBaseTest { private bool treatNullAsUniqueValue; @@ -32,25 +32,25 @@ public void Deadlock(bool first, IsolationLevel? isolationLevel, TransactionOpen { domain.WithStrategy(ExecuteActionStrategy.HandleUniqueConstraintViolation).WithIsolationLevel(isolationLevel.GetValueOrDefault(IsolationLevel.RepeatableRead)).WithTransactionOpenMode(transactionOpenMode.GetValueOrDefault(TransactionOpenMode.New)).Execute( session => { - Interlocked.Increment(ref Count); - new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; + _ = Interlocked.Increment(ref Count); + _ = new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; if (first) { - session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); - if (wait1!=null) { - wait1.Set(); - wait2.WaitOne(); + _ = session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); + if (wait1 != null) { + _ = wait1.Set(); + _ = wait2.WaitOne(); wait1 = null; } - session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); + _ = session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); } else { - session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); - if (wait2!=null) { - wait2.Set(); - wait1.WaitOne(); + _ = session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); + if (wait2 != null) { + _ = wait2.Set(); + _ = wait1.WaitOne(); wait2 = null; } - session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); + _ = session.Query.All().Lock(LockMode.Exclusive, LockBehavior.Wait).ToArray(); } }); } @@ -61,26 +61,27 @@ public void External( TransactionOpenMode? transactionOpenMode, Action action) { - using (Session session = domain.OpenSession()) - using (Xtensive.Orm.TransactionScope tran = isolationLevel==null ? null : session.OpenTransaction()) + using (var session = domain.OpenSession()) + using (var tran = isolationLevel == null ? null : session.OpenTransaction()) using (session.Activate()) { - if (tran!=null) { + if (tran != null) { session.EnsureTransactionIsStarted(); - new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; + _ = new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; } if (first) { - if (wait1!=null && wait2!=null) { - wait1.Set(); - wait2.WaitOne(); + if (wait1 != null && wait2 != null) { + _ = wait1.Set(); + _ = wait2.WaitOne(); } } - else if (wait1!=null && wait2!=null) { - wait2.Set(); - wait1.WaitOne(); + else if (wait1 != null && wait2 != null) { + _ = wait2.Set(); + _ = wait1.WaitOne(); } action(first, isolationLevel, transactionOpenMode); - if (tran!=null) + if (tran!=null) { tran.Complete(); + } } } @@ -94,16 +95,16 @@ public void Parent( domain.WithStrategy(strategy).WithIsolationLevel(isolationLevel.GetValueOrDefault(IsolationLevel.RepeatableRead)).WithTransactionOpenMode(transactionOpenMode.GetValueOrDefault(TransactionOpenMode.New)).Execute( session => { session.EnsureTransactionIsStarted(); - new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; + _ = new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; if (first) { - if (wait1!=null && wait2!=null) { - wait1.Set(); - wait2.WaitOne(); + if (wait1 != null && wait2 != null) { + _ = wait1.Set(); + _ = wait2.WaitOne(); } } else if (wait1!=null && wait2!=null) { - wait2.Set(); - wait1.WaitOne(); + _ = wait2.Set(); + _ = wait1.WaitOne(); } action(first, isolationLevel, transactionOpenMode); }); @@ -119,8 +120,8 @@ public void Run( session.Remove(session.Query.All()); session.Remove(session.Query.All()); session.Remove(session.Query.All()); - new Bar(session); - new Foo(session); + _ = new Bar(session); + _ = new Foo(session); }); Parallel.Invoke( () => action(true, isolationLevel, transactionOpenMode), @@ -132,24 +133,24 @@ public void UniqueConstraintViolation( { domain.WithStrategy(ExecuteActionStrategy.HandleUniqueConstraintViolation).WithIsolationLevel(isolationLevel.GetValueOrDefault(IsolationLevel.RepeatableRead)).WithTransactionOpenMode(transactionOpenMode.GetValueOrDefault(TransactionOpenMode.New)).Execute( session => { - Interlocked.Increment(ref Count); + _ = Interlocked.Increment(ref Count); session.EnsureTransactionIsStarted(); - new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; - string name = "test"; - if (!session.Query.All().Any(a => a.Name==name)) { + _ = new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; + var name = "test"; + if (!session.Query.All().Any(a => a.Name == name)) { if (first) { - if (wait1!=null && wait2!=null) { - wait1.Set(); - wait2.WaitOne(); + if (wait1 != null && wait2 != null) { + _ = wait1.Set(); + _ = wait2.WaitOne(); wait1 = null; } } - else if (wait2!=null && wait2!=null) { - wait2.Set(); - wait1.WaitOne(); + else if (wait2 != null && wait2 != null) { + _ = wait2.Set(); + _ = wait1.WaitOne(); wait2 = null; } - new Foo(session) {Name = name}; + _ = new Foo(session) {Name = name}; } session.SaveChanges(); }); @@ -160,26 +161,26 @@ public void UniqueConstraintViolationPrimaryKey( { domain.WithStrategy(ExecuteActionStrategy.HandleUniqueConstraintViolation).WithIsolationLevel(isolationLevel.GetValueOrDefault(IsolationLevel.RepeatableRead)).WithTransactionOpenMode(transactionOpenMode.GetValueOrDefault(TransactionOpenMode.New)).Execute( session => { - Interlocked.Increment(ref Count); + _ = Interlocked.Increment(ref Count); session.EnsureTransactionIsStarted(); - new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; - int id = 10; - if (session.Query.SingleOrDefault(id)==null) { - AutoResetEvent w1 = wait1; - AutoResetEvent w2 = wait2; + _ = new Bar2(session, DateTime.Now, Guid.NewGuid()) {Name = Guid.NewGuid().ToString()}; + var id = 10; + if (session.Query.SingleOrDefault(id) == null) { + var w1 = wait1; + var w2 = wait2; if (first) { - if (w1!=null && w2!=null) { - w1.Set(); - w2.WaitOne(); + if (w1 != null && w2 != null) { + _ = w1.Set(); + _ = w2.WaitOne(); wait1 = null; } } - else if (w1!=null && w2!=null) { - w2.Set(); - w1.WaitOne(); + else if (w1 != null && w2 != null) { + _ = w2.Set(); + _ = w1.WaitOne(); wait2 = null; } - new Foo(session, id) {Name = Guid.NewGuid().ToString()}; + _ = new Foo(session, id) { Name = Guid.NewGuid().ToString() }; } session.SaveChanges(); }); @@ -191,9 +192,9 @@ public Context(Domain domain) } } - public override void SetUp() + public override void TestFixtureSetUp() { - base.SetUp(); + base.TestFixtureSetUp(); treatNullAsUniqueValue = Domain.StorageProviderInfo.ProviderName == WellKnown.Provider.SqlServer; } diff --git a/Extensions/Xtensive.Orm.Security.Tests/AutoBuildTest.cs b/Extensions/Xtensive.Orm.Security.Tests/AutoBuildTest.cs deleted file mode 100644 index 802897c0b0..0000000000 --- a/Extensions/Xtensive.Orm.Security.Tests/AutoBuildTest.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System.Configuration; -using NUnit.Framework; -using System; -using TestCommon; -using Xtensive.Core; -using Xtensive.Orm; -using Xtensive.Orm.Configuration; -using Xtensive.Orm.Security.Tests.Model; -using Xtensive.Orm.Security.Tests.Roles; -using Xtensive.Reflection; - -namespace Xtensive.Orm.Security.Tests -{ - [TestFixture] - public abstract class AutoBuildTest - { - protected Domain Domain { get; private set; } - - [OneTimeSetUp] - public virtual void OneTimeSetUp() - { - var config = BuildConfiguration(); - Domain = BuildDomain(config); - PopulateData(); - } - - [OneTimeTearDown] - public virtual void OneTimeTearDown() - { - Domain.DisposeSafely(); - } - - protected virtual DomainConfiguration BuildConfiguration() - { - var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (Permission).Assembly); - configuration.Types.Register(typeof (AutoBuildTest).Assembly); - return configuration; - } - - protected virtual Domain BuildDomain(DomainConfiguration configuration) - { - try { - return Domain.Build(configuration); - } - catch (Exception e) { - Console.WriteLine(GetType().GetFullName()); - Console.WriteLine(e); - throw; - } - } - - protected virtual void PopulateData() - { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - - // Branches - var southBranch = new Branch(session) { Name = "South"}; - var northBranch = new Branch(session) { Name = "North"}; - - // Customers - new Customer(session) {IsAutomobileIndustry = true, Branch = southBranch}; - new VipCustomer(session) {IsAircraftIndustry = true, Reason = "High sales", Branch = southBranch}; - new VipCustomer(session) {Reason = "Relative", Branch = northBranch}; - - // Roles - var salesPersonRole = new SalesPersonRole(session); - var salesManagerRole = new SalesManagerRole(session); - var automobileManagerRole = new AutomobileManagerRole(session); - var aircraftManagerRole = new AircraftManagerRole(session); - var southBranchOfficeManager = new BranchOfficeManagerRole(session, southBranch); - var northBranchOfficeManager = new BranchOfficeManagerRole(session, northBranch); - - // Employees - var u1 = new Employee(session); - u1.Roles.Add(salesPersonRole); - u1.Name = "SalesPerson"; - - var u2 = new Employee(session); - u2.Roles.Add(salesManagerRole); - u2.Name = "SalesManager"; - - var u3 = new Employee(session); - u3.Roles.Add(automobileManagerRole); - u3.Name = "AutomobileManager"; - - var u4 = new Employee(session); - u4.Roles.Add(aircraftManagerRole); - u4.Name = "AircraftManager"; - - var u5 = new Employee(session); - u5.Roles.Add(southBranchOfficeManager); - u5.Name = "SouthBranchOfficeManager"; - - var u6 = new Employee(session); - u6.Roles.Add(northBranchOfficeManager); - u6.Name = "NorthBranchOfficeManager"; - - var u7 = new Employee(session); - u7.Roles.Add(southBranchOfficeManager); - u7.Roles.Add(northBranchOfficeManager); - u7.Name = "AllBranchOfficeManager"; - t.Complete(); - } - } - } - } -} diff --git a/Extensions/Xtensive.Orm.Security.Tests/SecurityTestBase.cs b/Extensions/Xtensive.Orm.Security.Tests/SecurityTestBase.cs new file mode 100644 index 0000000000..a8235b2a10 --- /dev/null +++ b/Extensions/Xtensive.Orm.Security.Tests/SecurityTestBase.cs @@ -0,0 +1,81 @@ +using System.Configuration; +using NUnit.Framework; +using System; +using TestCommon; +using Xtensive.Core; +using Xtensive.Orm; +using Xtensive.Orm.Configuration; +using Xtensive.Orm.Security.Tests.Model; +using Xtensive.Orm.Security.Tests.Roles; +using Xtensive.Reflection; +using Xtensive.Orm.Tests; + +namespace Xtensive.Orm.Security.Tests +{ + [TestFixture] + public abstract class SecurityTestBase : AutoBuildTest + { + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.Types.Register(typeof(Permission).Assembly); + configuration.Types.Register(typeof(SecurityTestBase).Assembly); + return configuration; + } + + protected override void PopulateData() + { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + + // Branches + var southBranch = new Branch(session) { Name = "South" }; + var northBranch = new Branch(session) { Name = "North" }; + + // Customers + _ = new Customer(session) { IsAutomobileIndustry = true, Branch = southBranch }; + _ = new VipCustomer(session) { IsAircraftIndustry = true, Reason = "High sales", Branch = southBranch }; + _ = new VipCustomer(session) { Reason = "Relative", Branch = northBranch }; + + // Roles + var salesPersonRole = new SalesPersonRole(session); + var salesManagerRole = new SalesManagerRole(session); + var automobileManagerRole = new AutomobileManagerRole(session); + var aircraftManagerRole = new AircraftManagerRole(session); + var southBranchOfficeManager = new BranchOfficeManagerRole(session, southBranch); + var northBranchOfficeManager = new BranchOfficeManagerRole(session, northBranch); + + // Employees + var u1 = new Employee(session); + _ = u1.Roles.Add(salesPersonRole); + u1.Name = "SalesPerson"; + + var u2 = new Employee(session); + _ = u2.Roles.Add(salesManagerRole); + u2.Name = "SalesManager"; + + var u3 = new Employee(session); + _ = u3.Roles.Add(automobileManagerRole); + u3.Name = "AutomobileManager"; + + var u4 = new Employee(session); + _ = u4.Roles.Add(aircraftManagerRole); + u4.Name = "AircraftManager"; + + var u5 = new Employee(session); + _ = u5.Roles.Add(southBranchOfficeManager); + u5.Name = "SouthBranchOfficeManager"; + + var u6 = new Employee(session); + _ = u6.Roles.Add(northBranchOfficeManager); + u6.Name = "NorthBranchOfficeManager"; + + var u7 = new Employee(session); + _ = u7.Roles.Add(southBranchOfficeManager); + _ = u7.Roles.Add(northBranchOfficeManager); + u7.Name = "AllBranchOfficeManager"; + t.Complete(); + } + } + } +} diff --git a/Extensions/Xtensive.Orm.Security.Tests/Tests/AuthenticationTests.cs b/Extensions/Xtensive.Orm.Security.Tests/Tests/AuthenticationTests.cs index 2caddf6014..4045f31993 100644 --- a/Extensions/Xtensive.Orm.Security.Tests/Tests/AuthenticationTests.cs +++ b/Extensions/Xtensive.Orm.Security.Tests/Tests/AuthenticationTests.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2011.06.10 @@ -11,32 +11,30 @@ namespace Xtensive.Orm.Security.Tests { - public class AuthenticationTests : AutoBuildTest + public class AuthenticationTests : SecurityTestBase { [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var trx = session.OpenTransaction()) { - - var employee = new Employee(session); - employee.Name = "Steve Ballmer"; - employee.SetPassword("developers, developers, developers, developers"); - Assert.That(employee.PasswordHash, Is.Not.Null.Or.Empty); + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { - trx.Complete(); - } + var employee = new Employee(session); + employee.Name = "Steve Ballmer"; + employee.SetPassword("developers, developers, developers, developers"); + Assert.That(employee.PasswordHash, Is.Not.Null.Or.Empty); + + trx.Complete(); } - using (var session = Domain.OpenSession()) { - using (var trx = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { - Assert.That(session.Authenticate("Steve Ballmer", "Steve Ballmer"), Is.Null); - Assert.That(session.Authenticate("developers, developers, developers, developers", "Steve Ballmer"), Is.Null); - Assert.That(session.Authenticate("Steve Ballmer", "developers, developers, developers, developers"), Is.Not.Null); + Assert.That(session.Authenticate("Steve Ballmer", "Steve Ballmer"), Is.Null); + Assert.That(session.Authenticate("developers, developers, developers, developers", "Steve Ballmer"), Is.Null); + Assert.That(session.Authenticate("Steve Ballmer", "developers, developers, developers, developers"), Is.Not.Null); - trx.Complete(); - } + trx.Complete(); } } } diff --git a/Extensions/Xtensive.Orm.Security.Tests/Tests/ConfigurationTests.cs b/Extensions/Xtensive.Orm.Security.Tests/Tests/ConfigurationTests.cs index 54d4b6118c..885724895a 100644 --- a/Extensions/Xtensive.Orm.Security.Tests/Tests/ConfigurationTests.cs +++ b/Extensions/Xtensive.Orm.Security.Tests/Tests/ConfigurationTests.cs @@ -1,12 +1,13 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2011.06.07 using NUnit.Framework; using TestCommon; using Xtensive.Orm.Security.Configuration; +using Xtensive.Orm.Tests; namespace Xtensive.Orm.Security.Tests { diff --git a/Extensions/Xtensive.Orm.Security.Tests/Tests/HashingServicesTests.cs b/Extensions/Xtensive.Orm.Security.Tests/Tests/HashingServicesTests.cs index ddacd59d5a..7f2506c251 100644 --- a/Extensions/Xtensive.Orm.Security.Tests/Tests/HashingServicesTests.cs +++ b/Extensions/Xtensive.Orm.Security.Tests/Tests/HashingServicesTests.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2011.05.30 @@ -14,9 +14,9 @@ namespace Xtensive.Orm.Security.Tests { [TestFixture] - public class HashingServicesTests : AutoBuildTest + public class HashingServicesTests : SecurityTestBase { - private List values; + private readonly List values; [Test] public void PlainHashingServiceTest() diff --git a/Extensions/Xtensive.Orm.Security.Tests/Tests/ImpersonationContextTests.cs b/Extensions/Xtensive.Orm.Security.Tests/Tests/ImpersonationContextTests.cs index 6cadbae27f..76d77d79ad 100644 --- a/Extensions/Xtensive.Orm.Security.Tests/Tests/ImpersonationContextTests.cs +++ b/Extensions/Xtensive.Orm.Security.Tests/Tests/ImpersonationContextTests.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2011.05.30 @@ -13,147 +13,143 @@ namespace Xtensive.Orm.Security.Tests { [TestFixture] - public class ImpersonationContextTests : AutoBuildTest + public class ImpersonationContextTests : SecurityTestBase { [Test] public void SessionImpersonateTest() { - using (var session = Domain.OpenSession()) { - using (var trx = session.OpenTransaction()) { - - var u = session.Query.All().First(); - var ic = session.Impersonate(u); - Assert.IsNotNull(ic); - Assert.IsNotNull(session.GetImpersonationContext()); - Assert.AreSame(ic, session.GetImpersonationContext()); - Assert.AreSame(u, ic.Principal); - - ic.Undo(); - Assert.IsNull(session.GetImpersonationContext()); - - // Should not fail in case multiple Undo - ic.Undo(); - ic.Undo(); - // Should not fail if Dispose after Undo - ic.Dispose(); - - ic = session.Impersonate(u); - ic.Dispose(); - Assert.IsNull(session.GetImpersonationContext()); - // Should not fail if Undo after Dispose - ic.Undo(); - - trx.Complete(); - } + using (var session = Domain.OpenSession()) + using (var trx = session.OpenTransaction()) { + + var u = session.Query.All().First(); + var ic = session.Impersonate(u); + Assert.IsNotNull(ic); + Assert.IsNotNull(session.GetImpersonationContext()); + Assert.AreSame(ic, session.GetImpersonationContext()); + Assert.AreSame(u, ic.Principal); + + ic.Undo(); + Assert.IsNull(session.GetImpersonationContext()); + + // Should not fail in case multiple Undo + ic.Undo(); + ic.Undo(); + // Should not fail if Dispose after Undo + ic.Dispose(); + + ic = session.Impersonate(u); + ic.Dispose(); + Assert.IsNull(session.GetImpersonationContext()); + // Should not fail if Undo after Dispose + ic.Undo(); + + trx.Complete(); } } [Test] public void NestedSessionImpersonationTest() { - using (var s = Domain.OpenSession()) { - using (var t = s.OpenTransaction()) { - - var users = s.Query.All().ToList(); - var u1 = users[0]; - var u2 = users[1]; - var ic1 = s.Impersonate(u1); - Assert.IsNotNull(ic1); - Assert.IsNotNull(s.GetImpersonationContext()); - Assert.AreSame(ic1, s.GetImpersonationContext()); - Assert.AreSame(u1, ic1.Principal); - - var ic2 = s.Impersonate(u2); - Assert.IsNotNull(ic2); - Assert.IsNotNull(s.GetImpersonationContext()); - Assert.AreSame(ic2, s.GetImpersonationContext()); - Assert.AreNotSame(ic1, ic2); - Assert.AreSame(u2, ic2.Principal); - - // Outer context can't be undone while is not active - ic1.Undo(); - Assert.AreSame(ic2, s.GetImpersonationContext()); - - ic2.Undo(); - // After outer context is undone, the nested one becomes outer - Assert.AreSame(ic1, s.GetImpersonationContext()); - - t.Complete(); - } + using (var s = Domain.OpenSession()) + using (var t = s.OpenTransaction()) { + + var users = s.Query.All().ToList(); + var u1 = users[0]; + var u2 = users[1]; + var ic1 = s.Impersonate(u1); + Assert.IsNotNull(ic1); + Assert.IsNotNull(s.GetImpersonationContext()); + Assert.AreSame(ic1, s.GetImpersonationContext()); + Assert.AreSame(u1, ic1.Principal); + + var ic2 = s.Impersonate(u2); + Assert.IsNotNull(ic2); + Assert.IsNotNull(s.GetImpersonationContext()); + Assert.AreSame(ic2, s.GetImpersonationContext()); + Assert.AreNotSame(ic1, ic2); + Assert.AreSame(u2, ic2.Principal); + + // Outer context can't be undone while is not active + ic1.Undo(); + Assert.AreSame(ic2, s.GetImpersonationContext()); + + ic2.Undo(); + // After outer context is undone, the nested one becomes outer + Assert.AreSame(ic1, s.GetImpersonationContext()); + + t.Complete(); } } [Test] public void SecureQueryTest() { - using (var s = Domain.OpenSession()) { - using (var t = s.OpenTransaction()) { + using (var s = Domain.OpenSession()) + using (var t = s.OpenTransaction()) { + + Assert.AreEqual(3, s.Query.All().Count()); + + var u1 = s.Query.All().Single(u => u.Name == "SalesPerson"); + using (var ic = s.Impersonate(u1)) { + + Assert.AreEqual(1, s.Query.All().Count()); + Assert.AreEqual(0, s.Query.All().Count()); + ic.Undo(); + } + + var u2 = s.Query.All().Single(u => u.Name == "SalesManager"); + using (var ic = s.Impersonate(u2)) { Assert.AreEqual(3, s.Query.All().Count()); + Assert.AreEqual(2, s.Query.All().Count()); + ic.Undo(); + } + + var u3 = s.Query.All().Single(u => u.Name == "AutomobileManager"); + using (var ic = s.Impersonate(u3)) { - var u1 = s.Query.All().Single(u => u.Name == "SalesPerson"); - using (var ic = s.Impersonate(u1)) { - - Assert.AreEqual(1, s.Query.All().Count()); - Assert.AreEqual(0, s.Query.All().Count()); - ic.Undo(); - } - - var u2 = s.Query.All().Single(u => u.Name == "SalesManager"); - using (var ic = s.Impersonate(u2)) { - - Assert.AreEqual(3, s.Query.All().Count()); - Assert.AreEqual(2, s.Query.All().Count()); - ic.Undo(); - } - - var u3 = s.Query.All().Single(u => u.Name == "AutomobileManager"); - using (var ic = s.Impersonate(u3)) { - - Assert.AreEqual(1, s.Query.All().Count()); - ic.Undo(); - } - - var u4 = s.Query.All().Single(u => u.Name == "AircraftManager"); - using (var ic = s.Impersonate(u4)) { - - Assert.AreEqual(1, s.Query.All().Count()); - ic.Undo(); - } - - // Merging 2 roles - u4.Roles.Add(s.Query.All().OfType().Single()); - using (var ic = s.Impersonate(u4)) { - - Assert.AreEqual(2, s.Query.All().Count()); - ic.Undo(); - } - - var u5 = s.Query.All().Single(u => u.Name == "SouthBranchOfficeManager"); - using (var ic = s.Impersonate(u5)) { - - Assert.AreEqual(2, s.Query.All().Count()); - ic.Undo(); - } - - var u6 = s.Query.All().Single(u => u.Name == "NorthBranchOfficeManager"); - using (var ic = s.Impersonate(u6)) { - - Assert.AreEqual(1, s.Query.All().Count()); - ic.Undo(); - } - - var u7 = s.Query.All().Single(u => u.Name == "AllBranchOfficeManager"); - using (var ic = s.Impersonate(u7)) { - - Assert.AreEqual(3, s.Query.All().Count()); - ic.Undo(); - } - - t.Complete(); + Assert.AreEqual(1, s.Query.All().Count()); + ic.Undo(); } + + var u4 = s.Query.All().Single(u => u.Name == "AircraftManager"); + using (var ic = s.Impersonate(u4)) { + + Assert.AreEqual(1, s.Query.All().Count()); + ic.Undo(); + } + + // Merging 2 roles + _ = u4.Roles.Add(s.Query.All().OfType().Single()); + using (var ic = s.Impersonate(u4)) { + + Assert.AreEqual(2, s.Query.All().Count()); + ic.Undo(); + } + + var u5 = s.Query.All().Single(u => u.Name == "SouthBranchOfficeManager"); + using (var ic = s.Impersonate(u5)) { + + Assert.AreEqual(2, s.Query.All().Count()); + ic.Undo(); + } + + var u6 = s.Query.All().Single(u => u.Name == "NorthBranchOfficeManager"); + using (var ic = s.Impersonate(u6)) { + + Assert.AreEqual(1, s.Query.All().Count()); + ic.Undo(); + } + + var u7 = s.Query.All().Single(u => u.Name == "AllBranchOfficeManager"); + using (var ic = s.Impersonate(u7)) { + + Assert.AreEqual(3, s.Query.All().Count()); + ic.Undo(); + } + + t.Complete(); } } - } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Security.Tests/Tests/PermissionSetTests.cs b/Extensions/Xtensive.Orm.Security.Tests/Tests/PermissionSetTests.cs index 61701982b6..af4f499fea 100644 --- a/Extensions/Xtensive.Orm.Security.Tests/Tests/PermissionSetTests.cs +++ b/Extensions/Xtensive.Orm.Security.Tests/Tests/PermissionSetTests.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2011.05.30 @@ -14,51 +14,49 @@ namespace Xtensive.Orm.Security.Tests { [TestFixture] - public class PermissionSetTests : AutoBuildTest + public class PermissionSetTests : SecurityTestBase { [Test] public void SalesManagerRoleTest() { - using (Session s = Domain.OpenSession()) { - using (TransactionScope t = s.OpenTransaction()) { - var role = new SalesManagerRole(s); - var roles = new List {role}; - var permissions = new PermissionSet(roles); - - Assert.AreEqual(role.Permissions.Count, permissions.Count); - Assert.IsTrue(permissions.Contains>(p => p.CanRead)); - Assert.IsTrue(permissions.Contains>(p => p.CanWrite)); - - Assert.IsTrue(permissions.Contains(p => p.CanRead)); - Assert.IsTrue(permissions.Contains(p => p.CanWrite)); - - Assert.IsTrue(permissions.Contains(p => p.CanRead)); - Assert.IsTrue(permissions.Contains(p => p.CanWrite)); - Assert.IsTrue(permissions.Contains(p => p.CanDiscount)); - } + using (var s = Domain.OpenSession()) + using (var t = s.OpenTransaction()) { + var role = new SalesManagerRole(s); + var roles = new List { role }; + var permissions = new PermissionSet(roles); + + Assert.AreEqual(role.Permissions.Count, permissions.Count); + Assert.IsTrue(permissions.Contains>(p => p.CanRead)); + Assert.IsTrue(permissions.Contains>(p => p.CanWrite)); + + Assert.IsTrue(permissions.Contains(p => p.CanRead)); + Assert.IsTrue(permissions.Contains(p => p.CanWrite)); + + Assert.IsTrue(permissions.Contains(p => p.CanRead)); + Assert.IsTrue(permissions.Contains(p => p.CanWrite)); + Assert.IsTrue(permissions.Contains(p => p.CanDiscount)); } } [Test] public void SalesPersonRoleTest() { - using (Session s = Domain.OpenSession()) { - using (TransactionScope t = s.OpenTransaction()) { - var role = new SalesPersonRole(s); - var roles = new List {role}; - var permissions = new PermissionSet(roles); - - Assert.AreEqual(role.Permissions.Count, permissions.Count); - Assert.IsTrue(permissions.Contains>(p => p.CanRead)); - Assert.IsTrue(permissions.Contains>(p => p.CanWrite)); - - Assert.IsTrue(permissions.Contains(p => p.CanRead)); - Assert.IsTrue(permissions.Contains(p => p.CanWrite)); - - Assert.IsFalse(permissions.Contains(p => p.CanRead)); - Assert.IsFalse(permissions.Contains(p => p.CanWrite)); - Assert.IsFalse(permissions.Contains(p => p.CanDiscount)); - } + using (var s = Domain.OpenSession()) + using (var t = s.OpenTransaction()) { + var role = new SalesPersonRole(s); + var roles = new List { role }; + var permissions = new PermissionSet(roles); + + Assert.AreEqual(role.Permissions.Count, permissions.Count); + Assert.IsTrue(permissions.Contains>(p => p.CanRead)); + Assert.IsTrue(permissions.Contains>(p => p.CanWrite)); + + Assert.IsTrue(permissions.Contains(p => p.CanRead)); + Assert.IsTrue(permissions.Contains(p => p.CanWrite)); + + Assert.IsFalse(permissions.Contains(p => p.CanRead)); + Assert.IsFalse(permissions.Contains(p => p.CanWrite)); + Assert.IsFalse(permissions.Contains(p => p.CanDiscount)); } } } diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/AutoBuildTest.cs b/Extensions/Xtensive.Orm.Tracking.Tests/AutoBuildTest.cs deleted file mode 100644 index 7efc93a30e..0000000000 --- a/Extensions/Xtensive.Orm.Tracking.Tests/AutoBuildTest.cs +++ /dev/null @@ -1,61 +0,0 @@ -using NUnit.Framework; -using System; -using TestCommon; -using Xtensive.Core; -using Xtensive.Orm.Tracking.Tests.Model; -using Xtensive.Reflection; -using Xtensive.Orm.Configuration; - -namespace Xtensive.Orm.Tracking.Tests -{ - [TestFixture] - public abstract class AutoBuildTest - { - protected Domain Domain { get; private set; } - - [SetUp] - public virtual void TestSetUp() - { - - } - - [TearDown] - public virtual void TestTearDown() - { - - } - - [OneTimeSetUp] - public virtual void TestFixtureSetUp() - { - var config = BuildConfiguration(); - Domain = BuildDomain(config); - } - - [OneTimeTearDown] - public virtual void TestFixtureTearDown() - { - Domain.DisposeSafely(); - } - - protected virtual DomainConfiguration BuildConfiguration() - { - var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (ITrackingMonitor).Assembly); - configuration.Types.Register(typeof (AutoBuildTest).Assembly); - return configuration; - } - - protected virtual Domain BuildDomain(DomainConfiguration configuration) - { - try { - return Domain.Build(configuration); - } - catch (Exception e) { - Console.WriteLine(GetType().GetFullName()); - Console.WriteLine(e); - throw; - } - } - } -} diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/ServiceRegistrationTest.cs b/Extensions/Xtensive.Orm.Tracking.Tests/ServiceRegistrationTest.cs index 7e5f32f0dc..a4c4ca2104 100644 --- a/Extensions/Xtensive.Orm.Tracking.Tests/ServiceRegistrationTest.cs +++ b/Extensions/Xtensive.Orm.Tracking.Tests/ServiceRegistrationTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2012 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2012-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2012.05.16 @@ -9,7 +9,7 @@ namespace Xtensive.Orm.Tracking.Tests { [TestFixture] - public class ServiceRegistrationTest : AutoBuildTest + public class ServiceRegistrationTest : TrackingTestBase { [Test] public void ShouldReturnInstanceOfTrackingMonitor() diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/TestHelper.cs b/Extensions/Xtensive.Orm.Tracking.Tests/TestHelper.cs index e3125261b0..f867e3ba3d 100644 --- a/Extensions/Xtensive.Orm.Tracking.Tests/TestHelper.cs +++ b/Extensions/Xtensive.Orm.Tracking.Tests/TestHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using Xtensive.Tuples; using Tuple = Xtensive.Tuples.Tuple; @@ -12,7 +12,7 @@ public static class TestHelper public static void Merge(ITrackingItem target, ITrackingItem source) { - MergeWithMethod.Invoke(target, new object[] {source}); + _ = MergeWithMethod.Invoke(target, new object[] {source}); } public static ITrackingItem CreateTrackingItem(Key key, TrackingItemState state) diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/TrackingItemTests.cs b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingItemTests.cs index 24338d1451..7331bc8908 100644 --- a/Extensions/Xtensive.Orm.Tracking.Tests/TrackingItemTests.cs +++ b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingItemTests.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2012 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2012-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2012.05.16 @@ -11,7 +11,7 @@ namespace Xtensive.Orm.Tracking.Tests { [TestFixture] - public class TrackingItemTests : AutoBuildTest + public class TrackingItemTests : TrackingTestBase { [Test] public void MergeNewAndNewTest() diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/TrackingMonitorTests.cs b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingMonitorTests.cs index 88f4637377..5366b8df8b 100644 --- a/Extensions/Xtensive.Orm.Tracking.Tests/TrackingMonitorTests.cs +++ b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingMonitorTests.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2012 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2012-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2012.05.17 @@ -12,7 +12,7 @@ namespace Xtensive.Orm.Tracking.Tests { [TestFixture] - public class TrackingMonitorTests : AutoBuildTest + public class TrackingMonitorTests : TrackingTestBase { private bool listenerIsCalled; diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/TrackingStackFrameTests.cs b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingStackFrameTests.cs index 98227c9c2a..a788d7940d 100644 --- a/Extensions/Xtensive.Orm.Tracking.Tests/TrackingStackFrameTests.cs +++ b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingStackFrameTests.cs @@ -1,93 +1,96 @@ -using System.Linq; +using System.Linq; using NUnit.Framework; +using Xtensive.Orm.Tracking; using Xtensive.Orm.Tracking.Tests.Model; namespace Xtensive.Orm.Tracking.Tests { [TestFixture] - public class TrackingStackFrameTests : AutoBuildTest + public class TrackingStackFrameTests : TrackingTestBase { -// [Test] -// public void SafelyInsertTheSameItemTwiceTest() -// { -// var frame = new TrackingStackFrame(); -// var key = Key.Create(Domain, typeof(MyEntity), 1); -// var item = TestHelper.CreateTrackingItem(key, TrackingItemState.Created); -// frame.Register(item); -// frame.Register(item); -// } -// -// [Test] -// public void MergeTwoEmptyFramesTest() -// { -// var target = new TrackingStackFrame(); -// var source = new TrackingStackFrame(); -// target.MergeWith(source); -// -// Assert.AreEqual(0, target.Count); -// } -// -// [Test] -// public void MergeEmptyFrameWithNonEmptyFrameTest() -// { -// var key = Key.Create(Domain, typeof(MyEntity), 1); -// var target = new TrackingStackFrame(); -// -// var source = new TrackingStackFrame(); -// source.Register(TestHelper.CreateTrackingItem(key, TrackingItemState.Created)); -// -// target.MergeWith(source); -// -// Assert.AreEqual(source.Count, target.Count); -// } -// -// [Test] -// public void MergeNonEmptyFrameWithEmptyFrameTest() -// { -// var key = Key.Create(Domain, typeof(MyEntity), 1); -// var target = new TrackingStackFrame(); -// target.Register(TestHelper.CreateTrackingItem(key, TrackingItemState.Created)); -// int count = target.Count; -// -// var source = new TrackingStackFrame(); -// -// target.MergeWith(source); -// -// Assert.AreEqual(count, target.Count); -// } -// -// [Test] -// public void MergeFramesWithTheSameItemsTest() -// { -// var key = Key.Create(Domain, typeof(MyEntity), 1); -// var target = new TrackingStackFrame(); -// target.Register(TestHelper.CreateTrackingItem(key, TrackingItemState.Created)); -// int count = target.Count; -// -// var source = new TrackingStackFrame(); -// source.Register(TestHelper.CreateTrackingItem(key, TrackingItemState.Changed)); -// -// target.MergeWith(source); -// -// Assert.AreEqual(count, target.Count); -// Assert.AreEqual(TrackingItemState.Created, target.Single().State); -// } -// -// [Test] -// public void MergeFramesWithDifferentItemsTest() -// { -// var key1 = Key.Create(Domain, typeof(MyEntity), 1); -// var key2 = Key.Create(Domain, typeof(MyEntity), 2); -// var target = new TrackingStackFrame(); -// target.Register(TestHelper.CreateTrackingItem(key1, TrackingItemState.Created)); -// -// var source = new TrackingStackFrame(); -// source.Register(TestHelper.CreateTrackingItem(key2, TrackingItemState.Changed)); -// int count = target.Count + source.Count; -// -// target.MergeWith(source); -// -// Assert.AreEqual(count, target.Count); -// } + [Test] + public void SafelyInsertTheSameItemTwiceTest() + { + var frame = new TrackingStackFrame(); + var key = Key.Create(Domain, typeof(MyEntity), 1); + var item = CreateTrackingItem(key, TrackingItemState.Created); + frame.Register(item); + frame.Register(item); + } + + [Test] + public void MergeTwoEmptyFramesTest() + { + var target = new TrackingStackFrame(); + var source = new TrackingStackFrame(); + target.MergeWith(source); + + Assert.AreEqual(0, target.Count); + } + + [Test] + public void MergeEmptyFrameWithNonEmptyFrameTest() + { + var key = Key.Create(Domain, typeof(MyEntity), 1); + var target = new TrackingStackFrame(); + + var source = new TrackingStackFrame(); + source.Register(CreateTrackingItem(key, TrackingItemState.Created)); + + target.MergeWith(source); + + Assert.AreEqual(source.Count, target.Count); + } + + [Test] + public void MergeNonEmptyFrameWithEmptyFrameTest() + { + var key = Key.Create(Domain, typeof(MyEntity), 1); + var target = new TrackingStackFrame(); + target.Register(CreateTrackingItem(key, TrackingItemState.Created)); + var count = target.Count; + + var source = new TrackingStackFrame(); + + target.MergeWith(source); + + Assert.AreEqual(count, target.Count); + } + + [Test] + public void MergeFramesWithTheSameItemsTest() + { + var key = Key.Create(Domain, typeof(MyEntity), 1); + var target = new TrackingStackFrame(); + target.Register(CreateTrackingItem(key, TrackingItemState.Created)); + var count = target.Count; + + var source = new TrackingStackFrame(); + source.Register(CreateTrackingItem(key, TrackingItemState.Changed)); + + target.MergeWith(source); + + Assert.AreEqual(count, target.Count); + Assert.AreEqual(TrackingItemState.Created, target.Single().State); + } + + [Test] + public void MergeFramesWithDifferentItemsTest() + { + var key1 = Key.Create(Domain, typeof(MyEntity), 1); + var key2 = Key.Create(Domain, typeof(MyEntity), 2); + var target = new TrackingStackFrame(); + target.Register(CreateTrackingItem(key1, TrackingItemState.Created)); + + var source = new TrackingStackFrame(); + source.Register(CreateTrackingItem(key2, TrackingItemState.Changed)); + var count = target.Count + source.Count; + + target.MergeWith(source); + + Assert.AreEqual(count, target.Count); + } + + private TrackingItem CreateTrackingItem(Key key, TrackingItemState state) => (TrackingItem) TestHelper.CreateTrackingItem(key, state); } } diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/TrackingTestBase.cs b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingTestBase.cs new file mode 100644 index 0000000000..d2f2ad604d --- /dev/null +++ b/Extensions/Xtensive.Orm.Tracking.Tests/TrackingTestBase.cs @@ -0,0 +1,33 @@ +using NUnit.Framework; +using System; +using TestCommon; +using Xtensive.Core; +using Xtensive.Orm.Tracking.Tests.Model; +using Xtensive.Reflection; +using Xtensive.Orm.Configuration; +using Xtensive.Orm.Tests; + +namespace Xtensive.Orm.Tracking.Tests +{ + [TestFixture] + public abstract class TrackingTestBase : AutoBuildTest + { + [SetUp] + public virtual void TestSetUp() + { + } + + [TearDown] + public virtual void TestTearDown() + { + } + + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.Types.Register(typeof(ITrackingMonitor).Assembly); + configuration.Types.Register(typeof(TrackingTestBase).Assembly); + return configuration; + } + } +} diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/Xtensive.Orm.Tracking.Tests.csproj b/Extensions/Xtensive.Orm.Tracking.Tests/Xtensive.Orm.Tracking.Tests.csproj index ed38c2ac38..008c56b3fc 100644 --- a/Extensions/Xtensive.Orm.Tracking.Tests/Xtensive.Orm.Tracking.Tests.csproj +++ b/Extensions/Xtensive.Orm.Tracking.Tests/Xtensive.Orm.Tracking.Tests.csproj @@ -1,8 +1,10 @@ - + ..\..\_Build\$(Configuration)\lib\ false + true + ..\Extensions.snk netcoreapp2.0 diff --git a/Extensions/Xtensive.Orm.Tracking/Properties/Visibility.cs b/Extensions/Xtensive.Orm.Tracking/Properties/Visibility.cs new file mode 100644 index 0000000000..906ea5031e --- /dev/null +++ b/Extensions/Xtensive.Orm.Tracking/Properties/Visibility.cs @@ -0,0 +1,12 @@ +// Copyright (C) 2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Xtensive.Orm.Tracking.Tests, PublicKey=" + +"00240000048000009400000006020000002400005253413100040000010001007f8790a0573a2a" + +"4f7b77907240977b669d33774bcaef77ef39d5186de4d4c836623fb661be674c7db731bc376184" + +"f6848fc6b64eeba506654c8212de624e9d1f15ad1fe765f769e9a5b59ecaab2866632a983e7828" + +"f3bf20ff7afffa021951cf8adc9ac1e786716430b0637893fb71b7566405fe14acc5e340c4af4a" + +"a293c994")] \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Tracking/Xtensive.Orm.Tracking.csproj b/Extensions/Xtensive.Orm.Tracking/Xtensive.Orm.Tracking.csproj index ba907993f8..9a1e6fa7c4 100644 --- a/Extensions/Xtensive.Orm.Tracking/Xtensive.Orm.Tracking.csproj +++ b/Extensions/Xtensive.Orm.Tracking/Xtensive.Orm.Tracking.csproj @@ -22,7 +22,4 @@ - - - \ No newline at end of file From 64d6f3207ca54301efa25954b76c3b114aa85a3d Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 17 Mar 2021 17:44:20 +0500 Subject: [PATCH 15/71] Correct FK extraction for SQLite --- .../Sql.Drivers.Sqlite/v3/Extractor.cs | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/Extractor.cs b/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/Extractor.cs index e3cf48da59..1f27d68582 100644 --- a/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/Extractor.cs +++ b/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/Extractor.cs @@ -181,34 +181,44 @@ private void ExtractIndexes() private void ExtractForeignKeys() { + // PRAGMA foreign_key_list - retuns column list for all foreign key + // row structure: + // 0 - id (numeric value, identifier, unique across foreign keys but non-unique across results) + // 1 - seq (numeric value, describes order within foreign key) + // 2 - table (string value, foreign table name) + // 3 - from (string value, local column name) + // 4 - to (string value, referenced column) + // 5 - on_update (string value, action on update) + // 6 - on_delete (string value, action on delete) + // 7 - match (string value, always NONE) + foreach (var table in schema.Tables) { var select = string.Format("PRAGMA foreign_key_list([{0}])", table.Name); - int lastColumnPosition = int.MaxValue; - ForeignKey constraint = null; + var lastColumnPosition = int.MaxValue; + ForeignKey foreignKey = null; Table referencingTable = null; Table referencedTable = null; using (var cmd = Connection.CreateCommand(select)) using (IDataReader reader = cmd.ExecuteReader()) { - ForeignKey foreignKey = null; while (reader.Read()) { - var foreignKeyName = String.Format(CultureInfo.InvariantCulture, "FK_{0}_{1}", referencingTable.Name, ReadStringOrNull(reader, 2)); + var columnPosition = ReadInt(reader, 1); - int columnPosition = ReadInt(reader, 5); if (columnPosition <= lastColumnPosition) { referencingTable = table; - constraint = referencingTable.CreateForeignKey(foreignKeyName); + var foreignKeyName = string.Format(CultureInfo.InvariantCulture, "FK_{0}_{1}", referencingTable.Name, ReadStringOrNull(reader, 2)); + foreignKey = referencingTable.CreateForeignKey(foreignKeyName); - ReadCascadeAction(constraint, reader, 7); + ReadCascadeAction(foreignKey, reader, 6); var referencedSchema = table.Schema; //Schema same as current referencedTable = referencedSchema.Tables[ReadStringOrNull(reader, 2)]; - constraint.ReferencedTable = referencedTable; + foreignKey.ReferencedTable = referencedTable; } var referencingColumn = referencingTable.TableColumns[reader.GetString(3)]; var referencedColumn = referencedTable.TableColumns[reader.GetString(4)]; - constraint.Columns.Add(referencingColumn); - constraint.ReferencedColumns.Add(referencedColumn); + foreignKey.Columns.Add(referencingColumn); + foreignKey.ReferencedColumns.Add(referencedColumn); lastColumnPosition = columnPosition; } } From fa64da0e7693b627a2164a7e3b0dd8f6a398881e Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 17 Mar 2021 21:33:07 +0500 Subject: [PATCH 16/71] Tests improvements for SQLite --- ...ssueJira0613_DataCleanUpInPerformSafely.cs | 8 +- ...ra0627_PocoClassPropertyRenitialization.cs | 742 +++++++++-------- ...umExpressionsAndConstantsTranslationBug.cs | 455 +++++----- .../Storage/ConstraintsTest.cs | 15 +- .../Storage/IgnoreRulesValidateTest.cs | 774 ++++++++++-------- 5 files changed, 1117 insertions(+), 877 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs index c28256a70b..3b451f3fad 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs @@ -186,11 +186,11 @@ private void RunTest(Action populateAction, Action validateAction, Type } else { // In this kind of tests we have only primary keys changed. - // To be clear, only name is changed. - // But MySQL has no named PKs so we have no difference in mysql + // To be clear, only name is changed, + // but this change is irrelevant for certain providers and comparison result is null var exception = Assert.Throws(() => Domain.Build(validationConfiguration)); - - if (validationConfiguration.ConnectionInfo.Provider != WellKnown.Provider.MySql) { + var provider = validationConfiguration.ConnectionInfo.Provider; + if (provider != WellKnown.Provider.MySql && provider != WellKnown.Provider.Sqlite) { Assert.That(exception.ComparisonResult, Is.Not.Null); } else { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs index 19db027d1e..a192454c9f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2015 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2015-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2015.12.31 @@ -21,12 +21,55 @@ public class IssueJira0627_PocoClassPropertyRenitialization : AutoBuildTest { private int businessUnitCount; + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.UpgradeMode = DomainUpgradeMode.Recreate; + configuration.Types.Register(typeof(BusinessUnit).Assembly, typeof(BusinessUnit).Namespace); + return configuration; + } + + protected override void PopulateData() + { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new BusinessUnit { Active = true, QuickbooksClass = "jdfhgkjhfdgjkhjhjh " }; + _ = new BusinessUnit { Active = true, QuickbooksClass = " jdfhgkgjkhjhjh " }; + _ = new BusinessUnit { Active = true, QuickbooksClass = " jdfhgkjhjdhfgfdgjkhjhjh" }; + _ = new BusinessUnit { Active = true, QuickbooksClass = "dfhgkaaaaajkhjhjh " }; + _ = new BusinessUnit { Active = true, QuickbooksClass = " jdfhgkjhfdgaaaaajh" }; + + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + _ = new TestEntity { Name = Guid.NewGuid().ToString() }; + + _ = new TestEntity { Name = "klegjkrlksl hdfhgh jhthkjhjth " }; + _ = new TestEntity { Name = " ohgoih oierigh oihreho hoiherigh oherg" }; + _ = new TestEntity { Name = "jshfhjhgjkherjghewogerogp reopertgo " }; + _ = new TestEntity { Name = "hjwroiheorihi oerhoigho hohergoh " }; + _ = new TestEntity { Name = "wieoru ioritgierh oiheroihg hoidfhgdf" }; + _ = new TestEntity { Name = "joijie oersidfgo dhhri " }; + _ = new TestEntity { Name = "fdg lhwoih jngoj bhoihiwht e" }; + _ = new TestEntity { Name = "rh ihh4i3hi ohierth094t pjpigd" }; + _ = new TestEntity { Name = "i049 hi0 4th 0fgi08 h03gh " }; + businessUnitCount = 5; + + transaction.Complete(); + } + } + [Test] public void MainTest() { using (var session = Domain.OpenSession()) using (var trasnaction = session.OpenTransaction()) { - List localClasses = new List(); + var localClasses = new List(); var buClassesLocal = ( from businessUnit in session.Query.All() where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) @@ -66,8 +109,8 @@ public void InitializationOnlyUsingConstructorParametersTest() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var buClasses = (from businessUnit in session.Query.All() - where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) - select new QboClassModel(businessUnit.Id, businessUnit.QuickbooksClass)).ToList(); + where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) + select new QboClassModel(businessUnit.Id, businessUnit.QuickbooksClass)).ToList(); foreach (var qboClassModel in buClasses) { Assert.That(qboClassModel.Name.StartsWith(" ") || qboClassModel.Name.EndsWith(" "), Is.False); @@ -86,8 +129,8 @@ public void PocoClassConstructorInsideQuery() from businessUnit in session.Query.All() where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) select new QboClassModel(businessUnit.Id, businessUnit.QuickbooksClass)) - where dto.Name.StartsWith(" ") - select dto.Name).ToList(); + where dto.Name.StartsWith(" ") + select dto.Name).ToList(); } } @@ -100,9 +143,9 @@ public void PocoClassObjectInitializerInsideQuery() ( from businessUnit in session.Query.All() where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) - select new Poco1() {Key = businessUnit.QuickbooksClass, Value = businessUnit.QuickbooksClass}) - where dto.Key.StartsWith(" ") - select dto.Value).ToList(); + select new Poco1() { Key = businessUnit.QuickbooksClass, Value = businessUnit.QuickbooksClass }) + where dto.Key.StartsWith(" ") + select dto.Value).ToList(); } } @@ -113,11 +156,12 @@ public void AnonymousTypeInitializationTest() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var buClasses = (from businessUnit in session.Query.All() - where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) - select new {businessUnit.Id, Name = businessUnit.QuickbooksClass}).ToList(); + where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) + select new { businessUnit.Id, Name = businessUnit.QuickbooksClass }).ToList(); - foreach (var qboClassModel in buClasses) + foreach (var qboClassModel in buClasses) { Assert.That(qboClassModel.Name.StartsWith(" ") || qboClassModel.Name.EndsWith(" "), Is.True); + } } } @@ -128,8 +172,8 @@ public void MixedInitialization() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var buClasses = (from businessUnit in session.Query.All() - where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) - select new QboClassModel(businessUnit.Id, businessUnit.QuickbooksClass) {SomeOtherField = businessUnit.QuickbooksClass}).ToList(); + where businessUnit.Active && !string.IsNullOrEmpty(businessUnit.QuickbooksClass) + select new QboClassModel(businessUnit.Id, businessUnit.QuickbooksClass) { SomeOtherField = businessUnit.QuickbooksClass }).ToList(); foreach (var qboClassModel in buClasses) { Assert.That(qboClassModel.Name.StartsWith(" ") || qboClassModel.Name.EndsWith(" "), Is.False); Assert.That(qboClassModel.SomeOtherField.StartsWith(" ") || qboClassModel.SomeOtherField.EndsWith(" "), Is.True); @@ -150,8 +194,9 @@ public void SimpleClassConstructorInitialization01() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var poco in query) - Assert.That(expected.Any(el=>el.Key==poco.Key && el.Value==poco.Value), Is.True); + foreach (var poco in query) { + Assert.That(expected.Any(el => el.Key == poco.Key && el.Value == poco.Value), Is.True); + } } } @@ -178,7 +223,7 @@ public void SimpleClassConstructorInitialization03() using (var transaction = session.OpenTransaction()) { var query = session.Query.All() .Select(el => new Poco0(el.QuickbooksClass, el.QuickbooksClass)) - .Select(el=>new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); var expected = session.Query.All() .AsEnumerable() .Select(el => new Poco0(el.QuickbooksClass, el.QuickbooksClass)) @@ -186,8 +231,9 @@ public void SimpleClassConstructorInitialization03() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var poco in query) - Assert.That(expected.Any(el => el.Key==poco.Key && el.Value==poco.Value), Is.True); + foreach (var poco in query) { + Assert.That(expected.Any(el => el.Key == poco.Key && el.Value == poco.Value), Is.True); + } } } @@ -223,8 +269,9 @@ public void SimpleClassConstructorInitialization05() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(expected.Count)); - foreach (var poco in query) - Assert.That(expected.Any(el => el.Key==poco.Key && el.Value==poco.Value), Is.True); + foreach (var poco in query) { + Assert.That(expected.Any(el => el.Key == poco.Key && el.Value == poco.Value), Is.True); + } } } @@ -257,8 +304,9 @@ public void SimpleClassConstructorInitialization07() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var poco in query) - Assert.That(expected.Any(el => el.Key==poco.Key && el.Value==poco.Value), Is.True); + foreach (var poco in query) { + Assert.That(expected.Any(el => el.Key == poco.Key && el.Value == poco.Value), Is.True); + } } } @@ -285,15 +333,16 @@ public void SimpleClassObjectInitialization01() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new Poco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}).ToList(); + .Select(el => new Poco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); var expected = session.Query.All() .AsEnumerable() .Select(el => new Poco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var poco in query) - Assert.That(expected.Any(el => el.Key==poco.Key && el.Value==poco.Value), Is.True); + foreach (var poco in query) { + Assert.That(expected.Any(el => el.Key == poco.Key && el.Value == poco.Value), Is.True); + } } } @@ -311,10 +360,10 @@ public void SimpleClassObjectInitialization02() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); foreach (var poco in query) { - var expectedPoco = expected.FirstOrDefault(el => el.Key==poco.Key); + var expectedPoco = expected.FirstOrDefault(el => el.Key == poco.Key); Assert.That(expectedPoco, Is.Not.Null); - Assert.That(expectedPoco.Value, Is.EqualTo(default (string))); - Assert.That(poco.Value, Is.EqualTo(default (string))); + Assert.That(expectedPoco.Value, Is.EqualTo(default(string))); + Assert.That(poco.Value, Is.EqualTo(default(string))); } } } @@ -325,17 +374,18 @@ public void SimpleClassObjectInitialization03() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new Poco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new Poco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new Poco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new Poco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var poco in query) - Assert.That(expected.Any(el => el.Key==poco.Key && el.Value==poco.Value), Is.True); + foreach (var poco in query) { + Assert.That(expected.Any(el => el.Key == poco.Key && el.Value == poco.Value), Is.True); + } } } @@ -345,12 +395,12 @@ public void SimpleClassObjectInitialization04() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new Poco1 {Key = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new Poco1 { Key = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new Poco1 {Key = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new Poco1 { Key = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); @@ -378,8 +428,9 @@ public void GenericClassConstructorInitialization01() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco0 in query) - Assert.That(expected.Any(el=>el.Key==genericPoco0.Key && el.Value==genericPoco0.Value)); + foreach (var genericPoco0 in query) { + Assert.That(expected.Any(el => el.Key == genericPoco0.Key && el.Value == genericPoco0.Value)); + } } } @@ -397,8 +448,9 @@ public void GenericClassConstructorInitialization02() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco0 in query) - Assert.That(expected.Any(el => el.Key==genericPoco0.Key && el.Value==genericPoco0.Value)); + foreach (var genericPoco0 in query) { + Assert.That(expected.Any(el => el.Key == genericPoco0.Key && el.Value == genericPoco0.Value)); + } } } @@ -470,8 +522,9 @@ public void GenericClassConstructorInitialization05() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco0 in query) - Assert.That(expected.Any(el => el.Key==genericPoco0.Key && el.Value==genericPoco0.Value)); + foreach (var genericPoco0 in query) { + Assert.That(expected.Any(el => el.Key == genericPoco0.Key && el.Value == genericPoco0.Value)); + } } } @@ -491,8 +544,9 @@ public void GenericClassConstructorInitialization06() Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco in query) - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); + foreach (var genericPoco in query) { + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); + } } } @@ -535,7 +589,7 @@ public void GenericClassConstructorInitialization08() var expected = session.Query.All() .AsEnumerable() .Select(el => new GenericPoco0()) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); @@ -558,16 +612,17 @@ public void GenericClassObjectInitialization01() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); Assert.That(query.Count, Is.EqualTo(5)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco in query) - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); + foreach (var genericPoco in query) { + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); + } } } @@ -577,17 +632,17 @@ public void GenericClassObjectInitialization02() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); foreach (var genericPoco in query) { - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); - Assert.That(genericPoco.Value==default(string)); + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); + Assert.That(genericPoco.Value == default(string)); } } } @@ -598,18 +653,19 @@ public void GenericClassObjectInitialization03() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco in query) - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); + foreach (var genericPoco in query) { + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); + } } } @@ -619,19 +675,19 @@ public void GenericClassObjectInitialization04() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); foreach (var genericPoco in query) { - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); - Assert.That(genericPoco.Value==default(string)); + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); + Assert.That(genericPoco.Value == default(string)); } } } @@ -642,16 +698,17 @@ public void GenericClassObjectInitialization05() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.Id, Value = el.Id}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id, Value = el.Id }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.Id, Value = el.Id}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id, Value = el.Id }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco in query) - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); + foreach (var genericPoco in query) { + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); + } } } @@ -661,10 +718,10 @@ public void GenericClassObjectInitialization06() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.Id}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.Id}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); @@ -682,18 +739,19 @@ public void GenericClassObjectInitialization07() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.Id, Value = el.Id}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id, Value = el.Id }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.Id, Value = el.Id}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id, Value = el.Id }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); - foreach (var genericPoco in query) - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); + foreach (var genericPoco in query) { + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); + } } } @@ -703,18 +761,18 @@ public void GenericClassObjectInitialization08() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new GenericPoco1 {Key = el.Id}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new GenericPoco1 {Key = el.Id}) - .Select(el => new {Key = el.Key, Value = el.Value}).ToList(); + .Select(el => new GenericPoco1 { Key = el.Id }) + .Select(el => new { Key = el.Key, Value = el.Value }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); foreach (var genericPoco in query) { - Assert.That(expected.Any(el => el.Key==genericPoco.Key && el.Value==genericPoco.Value)); + Assert.That(expected.Any(el => el.Key == genericPoco.Key && el.Value == genericPoco.Value)); Assert.That(genericPoco.Value == default(long)); } } @@ -811,11 +869,11 @@ public void DescendantClassConstructorInitializationTest04() using (var transaction = session.OpenTransaction()) { var query = session.Query.All() .Select(el => new DescendantPoco0(el.QuickbooksClass)) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); var expected = session.Query.All() .AsEnumerable() .Select(el => new DescendantPoco0(el.QuickbooksClass)) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); @@ -841,11 +899,11 @@ public void DescendantClassConstructorInitializationTest05() using (var transaction = session.OpenTransaction()) { var query = session.Query.All() .Select(el => new DescendantPoco0(el.QuickbooksClass, el.QuickbooksClass)) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); var expected = session.Query.All() .AsEnumerable() .Select(el => new DescendantPoco0(el.QuickbooksClass, el.QuickbooksClass)) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(expected.Count, Is.EqualTo(businessUnitCount)); @@ -871,7 +929,7 @@ public void DescendantClassConstructorInitializationTest06() using (var transaction = session.OpenTransaction()) { var query = session.Query.All() .Select(el => new DescendantPoco0(el.QuickbooksClass, el.QuickbooksClass, el.QuickbooksClass)) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); var expected = session.Query.All() .AsEnumerable() .Select(el => new DescendantPoco0(el.QuickbooksClass, el.QuickbooksClass, el.QuickbooksClass)) @@ -900,10 +958,10 @@ public void DescendantClassObjectInitializationTest01() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new DescendantPoco1 {AdditionalInfo = el.QuickbooksClass}).ToList(); + .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new DescendantPoco1 {AdditionalInfo = el.QuickbooksClass}).ToList(); + .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); @@ -928,15 +986,15 @@ public void DescendantClassObjectInitializationTest02() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new DescendantPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}).ToList(); + .Select(el => new DescendantPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new DescendantPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}).ToList(); + .Select(el => new DescendantPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); - foreach (var descendantPoco in expected){ + foreach (var descendantPoco in expected) { Assert.That(string.IsNullOrEmpty(descendantPoco.AdditionalInfo), Is.True); Assert.That(string.IsNullOrEmpty(descendantPoco.Key), Is.False); Assert.That(string.IsNullOrEmpty(descendantPoco.Value), Is.False); @@ -956,10 +1014,10 @@ public void DescendantClassObjectInitializationTest03() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new DescendantPoco1 {AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass}).ToList(); + .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new DescendantPoco1 {AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass}).ToList(); + .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); @@ -985,11 +1043,11 @@ public void DescendantClassObjectInitializationTest04() using (var transaction = session.OpenTransaction()) { var query = session.Query.All() .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass }) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new DescendantPoco1 {AdditionalInfo = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); @@ -1014,12 +1072,12 @@ public void DescendantClassObjectInitializationTest05() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new DescendantPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new DescendantPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new DescendantPoco1 {Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new DescendantPoco1 { Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); @@ -1044,12 +1102,12 @@ public void DescendantClassObjectInitializationTest06() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var query = session.Query.All() - .Select(el => new DescendantPoco1 {AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); var expected = session.Query.All() .AsEnumerable() - .Select(el => new DescendantPoco1 {AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass}) - .Select(el => new {Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo}).ToList(); + .Select(el => new DescendantPoco1 { AdditionalInfo = el.QuickbooksClass, Key = el.QuickbooksClass, Value = el.QuickbooksClass }) + .Select(el => new { Key = el.Key, Value = el.Value, AdditionalInfo = el.AdditionalInfo }).ToList(); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); Assert.That(query.Count, Is.EqualTo(businessUnitCount)); @@ -1073,8 +1131,8 @@ public void AllByFieldOfPoco01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name }) .All(el => el.Name.IsNullOrEmpty()); } } @@ -1084,7 +1142,7 @@ public void AllByFieldOfPoco02Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .All(el => el.Name.IsNullOrEmpty()); } @@ -1095,7 +1153,7 @@ public void AllByFieldOfPoco03Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .All(el => el.Name.IsNullOrEmpty()); } @@ -1106,8 +1164,8 @@ public void AllByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + _ = Assert.Throws(() => session.Query.All() + .Select(e => new Poco { BaseName = e.Name }) .All(el => el.Name.IsNullOrEmpty())); } } @@ -1117,7 +1175,7 @@ public void AllByFieldOfPoco05Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco()) .All(el => el.Name.IsNullOrEmpty()); } @@ -1129,8 +1187,9 @@ public void AnyByFieldOfPoco01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name}).Any(el => el.Name.IsNullOrEmpty()); + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name }) + .Any(el => el.Name.IsNullOrEmpty()); } } @@ -1139,7 +1198,7 @@ public void AnyByFieldOfPoco02Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Any(el => el.Name.IsNullOrEmpty()); } @@ -1150,8 +1209,8 @@ public void AnyByFieldOfPoco03Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Any(el => el.BaseName.IsNullOrEmpty()); } } @@ -1161,8 +1220,8 @@ public void AnyByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { BaseName = e.Name }) .Any(el => el.BaseName.IsNullOrEmpty()); } } @@ -1172,7 +1231,7 @@ public void AnyByFieldOfPoco05Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco()) .Any(el => el.Name.IsNullOrEmpty()); } @@ -1183,8 +1242,8 @@ public void AverageByFieldOfPoco01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name }) .Average(el => el.Name.Length); } } @@ -1194,8 +1253,8 @@ public void AverageByFieldOfPoco02Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Average(el => el.Name.Length); } } @@ -1205,8 +1264,8 @@ public void AverageByFieldOfPoco03Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Average(el => el.BaseName.Length); } } @@ -1216,8 +1275,8 @@ public void AverageByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { BaseName = e.Name }) .Average(el => el.BaseName.Length); } } @@ -1227,7 +1286,7 @@ public void AverageByFieldOfPoco05Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => session.Query.All() + _ = Assert.Throws(() => session.Query.All() .Select(e => new Poco()) .Average(el => el.Name.Length)); } @@ -1239,9 +1298,9 @@ public void ConcatOfPocos01Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) - .Concat(session.Query.All().Select(e => new Poco {Name = e.Name})) - .ToArray(); + .Select(e => new Poco { Name = e.Name }) + .Concat(session.Query.All().Select(e => new Poco { Name = e.Name })) + .Run(); } } @@ -1251,9 +1310,9 @@ public void ConcatOfPocos02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .Concat(session.Query.All().Select(e => new Poco {Name = e.Name, BaseName = e.Name})) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .Concat(session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name })) + .Run(); } } @@ -1265,7 +1324,7 @@ public void ConcatOfPocos03Test() session.Query.All() .Select(e => new Poco { BaseName = e.Name }) .Concat(session.Query.All().Select(e => new Poco { BaseName = e.Name })) - .ToArray(); + .Run(); } } @@ -1277,7 +1336,7 @@ public void ConcatOfPocos04Test() session.Query.All() .Select(e => new Poco()) .Concat(session.Query.All().Select(e => new Poco())) - .ToArray(); + .Run(); } } @@ -1286,8 +1345,8 @@ public void CountByFieldOfPoco01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name }) .Count(el => el.Name.IsNullOrEmpty()); } } @@ -1297,7 +1356,7 @@ public void CountByFieldOfPoco02Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Count(el => el.Name.IsNullOrEmpty()); } @@ -1308,7 +1367,7 @@ public void CountByFieldOfPoco03Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Count(el => el.BaseName.IsNullOrEmpty()); } @@ -1319,7 +1378,7 @@ public void CountByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() + _ = session.Query.All() .Select(e => new Poco { BaseName = e.Name }) .Count(el => el.BaseName.IsNullOrEmpty()); } @@ -1329,9 +1388,8 @@ public void CountByFieldOfPoco04Test() public void CountByFieldOfPoco05Test() { using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) - { - session.Query.All() + using (var transaction = session.OpenTransaction()) { + _ = session.Query.All() .Select(e => new Poco()) .Count(el => el.Name.IsNullOrEmpty()); } @@ -1341,12 +1399,11 @@ public void CountByFieldOfPoco05Test() public void DistinctOfPocos01Test() { using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) - { + using (var transaction = session.OpenTransaction()) { session.Query.All() .Select(e => new Poco { Name = e.Name }) .Distinct() - .ToArray(); + .Run(); } } @@ -1357,10 +1414,10 @@ public void ExceptOfPocos01Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) + .Select(e => new Poco { Name = e.Name }) .Except(session.Query.All() - .Select(e => new Poco {Name = e.Name})) - .ToArray(); + .Select(e => new Poco { Name = e.Name })) + .Run(); } } @@ -1371,10 +1428,10 @@ public void ExceptOfPocos02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Except(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name})) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name })) + .Run(); } } @@ -1385,10 +1442,10 @@ public void ExceptOfPocos03Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + .Select(e => new Poco { BaseName = e.Name }) .Except(session.Query.All() - .Select(e => new Poco {BaseName = e.Name})) - .ToArray(); + .Select(e => new Poco { BaseName = e.Name })) + .Run(); } } @@ -1402,7 +1459,7 @@ public void ExceptOfPocos05Test() .Select(e => new Poco()) .Except(session.Query.All() .Select(e => new Poco())) - .ToArray(); + .Run(); } } @@ -1412,9 +1469,9 @@ public void GroupByFieldOfPoco01Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) + .Select(e => new Poco { Name = e.Name }) .GroupBy(e => e.Name) - .ToArray(); + .Run(); } } @@ -1424,9 +1481,9 @@ public void GroupByFieldOfPoco02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .GroupBy(e => e.Name) - .ToArray(); + .Run(); } } @@ -1436,9 +1493,9 @@ public void GroupByFieldOfPoco03Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .GroupBy(e => e.BaseName) - .ToArray(); + .Run(); } } @@ -1447,10 +1504,10 @@ public void GroupByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(()=>session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + _ = Assert.Throws(() => session.Query.All() + .Select(e => new Poco { BaseName = e.Name }) .GroupBy(e => e.Name) - .ToArray()); + .Run()); } } @@ -1462,7 +1519,7 @@ public void GroupByFieldOfPoco05Test() session.Query.All() .Select(e => new Poco()) .GroupBy(e => e.Name) - .ToArray(); + .Run(); } } @@ -1472,10 +1529,13 @@ public void GroupJoinOfPoco01Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) - .GroupJoin(session.Query.All() - .Select(e => new Poco {Name = e.Name}), (poco) => poco.Name, poco => poco.Name, (poco, pocos) => new {Key = poco.Name, Values = pocos}) - .ToArray(); + .Select(e => new Poco { Name = e.Name }) + .GroupJoin( + session.Query.All().Select(e => new Poco { Name = e.Name }), + (poco) => poco.Name, + poco => poco.Name, + (poco, pocos) => new { Key = poco.Name, Values = pocos }) + .Run(); } } @@ -1485,10 +1545,13 @@ public void GroupJoinOfPoco02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .GroupJoin(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}), (poco) => poco.Name, poco => poco.Name, (poco, pocos) => new {Key = poco.Name, Values = pocos}) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .GroupJoin( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + (poco) => poco.Name, + poco => poco.Name, + (poco, pocos) => new { Key = poco.Name, Values = pocos }) + .Run(); } } @@ -1498,10 +1561,13 @@ public void GroupJoinOfPocos03Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .GroupJoin(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}), (poco) => poco.Name, poco => poco.BaseName, (poco, pocos) => new {Key = poco.Name, Values = pocos}) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .GroupJoin( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + (poco) => poco.Name, + poco => poco.BaseName, + (poco, pocos) => new { Key = poco.Name, Values = pocos }) + .Run(); } } @@ -1511,10 +1577,13 @@ public void GroupJoinOfPocos04Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .GroupJoin(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}), (poco) => poco.BaseName, poco => poco.Name, (poco, pocos) => new {Key = poco.BaseName, Values = pocos}) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .GroupJoin( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + (poco) => poco.BaseName, + poco => poco.Name, + (poco, pocos) => new { Key = poco.BaseName, Values = pocos }) + .Run(); } } @@ -1524,10 +1593,13 @@ public void GroupJoinOfPocos05Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .GroupJoin(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}), (poco) => poco.BaseName, poco => poco.BaseName, (poco, pocos) => new {Key = poco.BaseName, Values = pocos}) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .GroupJoin( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + (poco) => poco.BaseName, + poco => poco.BaseName, + (poco, pocos) => new { Key = poco.BaseName, Values = pocos }) + .Run(); } } @@ -1537,10 +1609,13 @@ public void GroupJoinOfPocos06Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) - .GroupJoin(session.Query.All() - .Select(e => new Poco {BaseName = e.Name}), (poco) => poco.BaseName, poco => poco.BaseName, (poco, pocos) => new {Key = poco.BaseName, Values = pocos}) - .ToArray(); + .Select(e => new Poco { BaseName = e.Name }) + .GroupJoin( + session.Query.All().Select(e => new Poco { BaseName = e.Name }), + (poco) => poco.BaseName, + poco => poco.BaseName, + (poco, pocos) => new { Key = poco.BaseName, Values = pocos }) + .Run(); } } @@ -1554,7 +1629,7 @@ public void IntersectOfPocos01Test() .Select(e => new Poco { Name = e.Name }) .Except(session.Query.All() .Select(e => new Poco { Name = e.Name })) - .ToArray(); + .Run(); } } @@ -1568,7 +1643,7 @@ public void IntersectOfPocos02Test() .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Intersect(session.Query.All() .Select(e => new Poco { Name = e.Name, BaseName = e.Name })) - .ToArray(); + .Run(); } } @@ -1582,7 +1657,7 @@ public void IntersectOfPocos03Test() .Select(e => new Poco { BaseName = e.Name }) .Intersect(session.Query.All() .Select(e => new Poco { BaseName = e.Name })) - .ToArray(); + .Run(); } } @@ -1596,21 +1671,24 @@ public void IntersectOfPocos05Test() .Select(e => new Poco()) .Intersect(session.Query.All() .Select(e => new Poco())) - .ToArray(); + .Run(); } } - + [Test] public void JoinOfPocos01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) - .Join(session.Query.All() - .Select(e => new Poco {Name = e.Name}), poco => poco.Name, poco => poco.Name, (poco, poco1) => new {poco, poco1}) - .ToArray(); + .Select(e => new Poco { Name = e.Name }) + .Join( + session.Query.All().Select(e => new Poco { Name = e.Name }), + poco => poco.Name, + poco => poco.Name, + (poco, poco1) => new { poco, poco1 }) + .Run(); } } @@ -1620,10 +1698,13 @@ public void JoinOfPoco02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .Join(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}), poco => poco.Name, poco => poco.Name, (poco, poco1) => new {poco, poco1}) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .Join( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + poco => poco.Name, + poco => poco.Name, + (poco, poco1) => new { poco, poco1 }) + .Run(); } } @@ -1633,10 +1714,13 @@ public void JoinOfPocos03Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .Join(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}), poco => poco.BaseName, poco => poco.Name, (poco, poco1) => new {poco, poco1}) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .Join( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + poco => poco.BaseName, + poco => poco.Name, + (poco, poco1) => new { poco, poco1 }) + .Run(); } } @@ -1647,9 +1731,12 @@ public void JoinOfPocos04Test() using (var transaction = session.OpenTransaction()) { session.Query.All() .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) - .Join(session.Query.All() - .Select(e => new Poco { Name = e.Name, BaseName = e.Name }), poco => poco.Name, poco => poco.BaseName, (poco, poco1) => new { poco, poco1 }) - .ToArray(); + .Join( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + poco => poco.Name, + poco => poco.BaseName, + (poco, poco1) => new { poco, poco1 }) + .Run(); } } @@ -1659,10 +1746,13 @@ public void JoinOfPocos05Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) - .Join(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}), poco => poco.BaseName, poco => poco.BaseName, (poco, poco1) => new {poco, poco1}) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .Join( + session.Query.All().Select(e => new Poco { Name = e.Name, BaseName = e.Name }), + poco => poco.BaseName, + poco => poco.BaseName, + (poco, poco1) => new { poco, poco1 }) + .Run(); } } @@ -1672,10 +1762,10 @@ public void JoinOfPocos06Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + .Select(e => new Poco { BaseName = e.Name }) .Join(session.Query.All() - .Select(e => new Poco {BaseName = e.Name}), poco => poco.BaseName, poco => poco.BaseName, (poco, poco1) => new {poco, poco1}) - .ToArray(); + .Select(e => new Poco { BaseName = e.Name }), poco => poco.BaseName, poco => poco.BaseName, (poco, poco1) => new { poco, poco1 }) + .Run(); } } @@ -1684,8 +1774,8 @@ public void MaxByFieldOfPoco01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name }) .Max(el => el.Name.Length); } } @@ -1695,8 +1785,8 @@ public void MaxByFieldOfPoco02Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Max(el => el.Name.Length + el.BaseName.Length); } } @@ -1706,8 +1796,8 @@ public void MaxByFieldOfPoco03Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { BaseName = e.Name }) .Max(el => el.BaseName.Length); } } @@ -1717,7 +1807,7 @@ public void MaxByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => session.Query.All() + _ = Assert.Throws(() => session.Query.All() .Select(e => new Poco()) .Max(el => el.Name.Length)); } @@ -1728,8 +1818,8 @@ public void MinByFieldOfPoco01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name }) .Min(el => el.Name.Length); } } @@ -1739,8 +1829,8 @@ public void MinByFieldOfPoco02Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Min(el => el.Name.Length + el.BaseName.Length); } } @@ -1750,8 +1840,8 @@ public void MinByFieldOfPoco03Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + _ = session.Query.All() + .Select(e => new Poco { BaseName = e.Name }) .Min(el => el.BaseName.Length); } } @@ -1761,7 +1851,7 @@ public void MinByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => session.Query.All() + _ = Assert.Throws(() => session.Query.All() .Select(e => new Poco()) .Min(el => el.Name.Length)); } @@ -1773,9 +1863,9 @@ public void OrderByFieldOfPoco01Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) + .Select(e => new Poco { Name = e.Name }) .OrderBy(e => e.Name) - .ToArray(); + .Run(); } } @@ -1785,9 +1875,9 @@ public void OrderByFieldOfPoco02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .OrderBy(e => e.Name) - .ToArray(); + .Run(); } } @@ -1797,9 +1887,9 @@ public void OrderByFieldOfPoco03Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .OrderBy(e => e.BaseName) - .ToArray(); + .Run(); } } @@ -1808,32 +1898,41 @@ public void OrderByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => + _ = Assert.Throws(() => session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + .Select(e => new Poco { BaseName = e.Name }) .OrderBy(e => e.Name) - .ToArray()); + .Run()); } } [Test] public void OrderByFieldOfPoco05Test() { - Require.ProviderIsNot(StorageProvider.Firebird | StorageProvider.MySql); + RequireProviderDeniesOrderByNull(); + using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - if (ProviderAllowsOrderByNull()) - Assert.DoesNotThrow(() => - session.Query.All() - .Select(e => new Poco()) - .OrderBy(e => e.Name) - .ToArray()); - else - Assert.Throws(() => - session.Query.All() - .Select(e => new Poco()) - .OrderBy(e => e.Name) - .ToArray()); + _ = Assert.Throws(() => + session.Query.All() + .Select(e => new Poco()) + .OrderBy(e => e.Name) + .Run()); + } + } + + [Test] + public void OrderByFieldOfPoco06Test() + { + RequireProviderAllowsOrderByNull(); + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + Assert.DoesNotThrow(() => + session.Query.All() + .Select(e => new Poco()) + .OrderBy(e => e.Name) + .Run()); } } @@ -1843,9 +1942,9 @@ public void OrderByDescendingByFieldOfPoco01Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) + .Select(e => new Poco { Name = e.Name }) .OrderByDescending(e => e.Name) - .ToArray(); + .Run(); } } @@ -1855,9 +1954,9 @@ public void OrderByDescendingByFieldOfPoco02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .OrderByDescending(e => e.Name) - .ToArray(); + .Run(); } } @@ -1867,9 +1966,9 @@ public void OrderByDescendingByFieldOfPoco03Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .OrderByDescending(e => e.BaseName) - .ToArray(); + .Run(); } } @@ -1878,25 +1977,41 @@ public void OrderByDescendingByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => + _ = Assert.Throws(() => session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + .Select(e => new Poco { BaseName = e.Name }) .OrderByDescending(e => e.Name) - .ToArray()); + .Run()); } } [Test] public void OrderByDescendingByFieldOfPoco05Test() { - Require.ProviderIsNot(StorageProvider.Firebird | StorageProvider.MySql | StorageProvider.PostgreSql); + RequireProviderDeniesOrderByNull(); + using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => + _ = Assert.Throws(() => session.Query.All() .Select(e => new Poco()) .OrderByDescending(e => e.Name) - .ToArray()); + .Run()); + } + } + + [Test] + public void OrderByDescendingByFieldOfPoco06Test() + { + RequireProviderAllowsOrderByNull(); + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + Assert.DoesNotThrow(() => + session.Query.All() + .Select(e => new Poco()) + .OrderByDescending(e => e.Name) + .Run()); } } @@ -1905,8 +2020,8 @@ public void SumByFieldOfPoco01Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name}).Sum(el => el.Name.Length); + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name }).Sum(el => el.Name.Length); } } @@ -1915,8 +2030,9 @@ public void SumByFieldOfPoco02Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}).Sum(el => el.Name.Length + el.BaseName.Length); + _ = session.Query.All() + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) + .Sum(el => el.Name.Length + el.BaseName.Length); } } @@ -1925,8 +2041,8 @@ public void SumByFieldOfPoco03Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - session.Query.All() - .Select(e => new Poco {BaseName = e.Name}).Sum(el => el.BaseName.Length); + _ = session.Query.All() + .Select(e => new Poco { BaseName = e.Name }).Sum(el => el.BaseName.Length); } } @@ -1935,7 +2051,7 @@ public void SumByFieldOfPoco04Test() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => + _ = Assert.Throws(() => session.Query.All() .Select(e => new Poco()).Sum(el => el.Name.Length)); } @@ -1947,10 +2063,10 @@ public void UnionOfPocos01Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name}) + .Select(e => new Poco { Name = e.Name }) .Union(session.Query.All() - .Select(e => new Poco {Name = e.Name})) - .ToArray(); + .Select(e => new Poco { Name = e.Name })) + .Run(); } } @@ -1960,10 +2076,10 @@ public void UnionOfPocos02Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name}) + .Select(e => new Poco { Name = e.Name, BaseName = e.Name }) .Union(session.Query.All() - .Select(e => new Poco {Name = e.Name, BaseName = e.Name})) - .ToArray(); + .Select(e => new Poco { Name = e.Name, BaseName = e.Name })) + .Run(); } } @@ -1973,10 +2089,10 @@ public void UnionOfPocos03Test() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Query.All() - .Select(e => new Poco {BaseName = e.Name}) + .Select(e => new Poco { BaseName = e.Name }) .Union(session.Query.All() - .Select(e => new Poco {BaseName = e.Name})) - .ToArray(); + .Select(e => new Poco { BaseName = e.Name })) + .Run(); } } @@ -1989,56 +2105,20 @@ public void UnionOfPocos05Test() .Select(e => new Poco()) .Union(session.Query.All() .Select(e => new Poco())) - .ToArray(); + .Run(); } } - private bool ProviderAllowsOrderByNull() + private void RequireProviderDeniesOrderByNull() { - var providers = new[] {WellKnown.Provider.PostgreSql}; - return providers.Contains(ProviderInfo.ProviderName); + Require.ProviderIsNot(StorageProvider.Sqlite | StorageProvider.PostgreSql | + StorageProvider.MySql | StorageProvider.Firebird); } - protected override void PopulateData() + private void RequireProviderAllowsOrderByNull() { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new BusinessUnit {Active = true, QuickbooksClass = "jdfhgkjhfdgjkhjhjh "}; - new BusinessUnit {Active = true, QuickbooksClass = " jdfhgkgjkhjhjh "}; - new BusinessUnit {Active = true, QuickbooksClass = " jdfhgkjhjdhfgfdgjkhjhjh"}; - new BusinessUnit {Active = true, QuickbooksClass = "dfhgkaaaaajkhjhjh "}; - new BusinessUnit {Active = true, QuickbooksClass = " jdfhgkjhfdgaaaaajh"}; - - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - new TestEntity {Name = Guid.NewGuid().ToString()}; - - new TestEntity {Name = "klegjkrlksl hdfhgh jhthkjhjth "}; - new TestEntity {Name = " ohgoih oierigh oihreho hoiherigh oherg"}; - new TestEntity {Name = "jshfhjhgjkherjghewogerogp reopertgo "}; - new TestEntity {Name = "hjwroiheorihi oerhoigho hohergoh "}; - new TestEntity {Name = "wieoru ioritgierh oiheroihg hoidfhgdf"}; - new TestEntity {Name = "joijie oersidfgo dhhri "}; - new TestEntity {Name = "fdg lhwoih jngoj bhoihiwht e"}; - new TestEntity {Name = "rh ihh4i3hi ohierth094t pjpigd"}; - new TestEntity {Name = "i049 hi0 4th 0fgi08 h03gh "}; - businessUnitCount = 5; - transaction.Complete(); - } - } - - protected override DomainConfiguration BuildConfiguration() - { - var configuration = base.BuildConfiguration(); - configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (BusinessUnit).Assembly, typeof(BusinessUnit).Namespace); - return configuration; + Require.ProviderIs(StorageProvider.Sqlite | StorageProvider.PostgreSql | + StorageProvider.MySql | StorageProvider.Firebird); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0659_EnumExpressionsAndConstantsTranslationBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0659_EnumExpressionsAndConstantsTranslationBug.cs index 3c7a2711ed..b5020a635b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0659_EnumExpressionsAndConstantsTranslationBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0659_EnumExpressionsAndConstantsTranslationBug.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.08.08 @@ -178,17 +178,50 @@ public class IssueJira0659_EnumExpressionsAndConstantsTranslationBug : AutoBuild private readonly DateTime secondDateTime = new DateTime(2014, 12, 10); private readonly DateTime defaultDateTime = new DateTime(2012, 12, 12); + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.UpgradeMode = DomainUpgradeMode.Recreate; + configuration.Types.Register(typeof(EntityWithGender).Assembly, typeof(EntityWithGender).Namespace); + return configuration; + } + + protected override void PopulateData() + { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new EntityWithGender { Gender = Gender.Male }; + _ = new EntityWithGender { Gender = Gender.Female, NullableGender = Gender.Female }; + + _ = new EntityWithExtendedGender { Gender = ExtendedGender.Male }; + _ = new EntityWithExtendedGender { Gender = ExtendedGender.Female, NullableGender = ExtendedGender.Female }; + + _ = new EntityWithIntFlags { Flags = SomeIntFlags.Flag1 | SomeIntFlags.Flag20 }; + _ = new EntityWithIntFlags { Flags = SomeIntFlags.Flag1 | SomeIntFlags.Flag10, NullableFlags = SomeIntFlags.Flag10 }; + + _ = new EntityWithLongFlags { Flags = SomeLongFlags.Flag1 | SomeLongFlags.Flag20 }; + _ = new EntityWithLongFlags { Flags = SomeLongFlags.Flag1 | SomeLongFlags.Flag20, NullableFlags = SomeLongFlags.Flag10 }; + + _ = new EntityWithDateTime { DateTime = firstDateTime }; + _ = new EntityWithDateTime { DateTime = secondDateTime, NullableDateTime = nullableFieldDateTime }; + + _ = new EntityWithInt { Int = 20 }; + _ = new EntityWithInt { Int = 20, NullableInt = 10 }; + transaction.Complete(); + } + } + [Test] public void DirectGroupByByNotNullEnum() { Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.Gender) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g=> g.Key==Gender.Male)); - Assert.That(result.Any(g=>g.Key==Gender.Female)); + Assert.That(result.Any(g => g.Key == Gender.Male)); + Assert.That(result.Any(g => g.Key == Gender.Female)); }; RunTestInSession(testAction); @@ -200,11 +233,11 @@ public void DirectGroupByByConditionalOperatorForIntEnumTest() Action testAction = (session) => { var genderGroups = session.Query.All() .GroupBy(x => x.NullableGender.HasValue ? x.NullableGender.Value : Gender.None) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==Gender.None)); - Assert.That(genderGroups.Any(g => g.Key==Gender.Female)); + Assert.That(genderGroups.Any(g => g.Key == Gender.None)); + Assert.That(genderGroups.Any(g => g.Key == Gender.Female)); }; RunTestInSession(testAction); } @@ -215,11 +248,11 @@ public void DirectGroupByByConditionalOperatorForLongEnumTest() Action testAction = (session) => { var genderGroups = session.Query.All() .GroupBy(x => x.NullableGender.HasValue ? x.NullableGender.Value : ExtendedGender.None) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==ExtendedGender.None)); - Assert.That(genderGroups.Any(g => g.Key==ExtendedGender.Female)); + Assert.That(genderGroups.Any(g => g.Key == ExtendedGender.None)); + Assert.That(genderGroups.Any(g => g.Key == ExtendedGender.Female)); }; RunTestInSession(testAction); } @@ -230,11 +263,11 @@ public void DirectGroupByByConditionalOperatorForIntFlagTest() Action testAction = (session) => { var genderGroups = session.Query.All() .GroupBy(x => x.NullableFlags.HasValue ? x.NullableFlags.Value : SomeIntFlags.None) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==SomeIntFlags.None)); - Assert.That(genderGroups.Any(g => g.Key==SomeIntFlags.Flag10)); + Assert.That(genderGroups.Any(g => g.Key == SomeIntFlags.None)); + Assert.That(genderGroups.Any(g => g.Key == SomeIntFlags.Flag10)); }; RunTestInSession(testAction); } @@ -248,8 +281,8 @@ public void DirectGroupByByConditionalOperatorForLongFlagTest() .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==SomeLongFlags.None)); - Assert.That(genderGroups.Any(g => g.Key==SomeLongFlags.Flag10)); + Assert.That(genderGroups.Any(g => g.Key == SomeLongFlags.None)); + Assert.That(genderGroups.Any(g => g.Key == SomeLongFlags.Flag10)); }; RunTestInSession(testAction); } @@ -260,11 +293,11 @@ public void DirectGroupByByConditionalOperatorForDateTimeTest() Action testAction = (session) => { var genderGroups = session.Query.All() .GroupBy(x => x.NullableDateTime.HasValue ? x.NullableDateTime.Value : new DateTime(2012, 12, 12)) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==new DateTime(2012, 12, 12))); - Assert.That(genderGroups.Any(g => g.Key==nullableFieldDateTime)); + Assert.That(genderGroups.Any(g => g.Key == new DateTime(2012, 12, 12))); + Assert.That(genderGroups.Any(g => g.Key == nullableFieldDateTime)); }; RunTestInSession(testAction); } @@ -275,11 +308,11 @@ public void DirectGroupByByConditionalOperatorForIntTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableInt.HasValue ? x.NullableInt : -1) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==-1)); - Assert.That(result.Any(g => g.Key==10)); + Assert.That(result.Any(g => g.Key == -1)); + Assert.That(result.Any(g => g.Key == 10)); }; RunTestInSession(testAction); } @@ -294,11 +327,11 @@ public void IndirectGroupByByConditionalOperatorForIntEnumTest() Gender = el.NullableGender.HasValue ? el.NullableGender.Value : Gender.None }) .GroupBy(x => x.Gender) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==Gender.None)); - Assert.That(genderGroups.Any(g => g.Key==Gender.Female)); + Assert.That(genderGroups.Any(g => g.Key == Gender.None)); + Assert.That(genderGroups.Any(g => g.Key == Gender.Female)); }; RunTestInSession(testAction); } @@ -313,11 +346,11 @@ public void IndirectGroupByByConditionalOperatorForLongEnumTest() Gender = el.NullableGender.HasValue ? el.NullableGender.Value : ExtendedGender.None }) .GroupBy(x => x.Gender) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==ExtendedGender.None)); - Assert.That(genderGroups.Any(g => g.Key==ExtendedGender.Female)); + Assert.That(genderGroups.Any(g => g.Key == ExtendedGender.None)); + Assert.That(genderGroups.Any(g => g.Key == ExtendedGender.Female)); }; RunTestInSession(testAction); } @@ -332,11 +365,11 @@ public void IndirectGroupByByConditionalOperatorForIntFlagTest() Flags = el.NullableFlags.HasValue ? el.NullableFlags.Value : SomeIntFlags.None }) .GroupBy(x => x.Flags) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==SomeIntFlags.None)); - Assert.That(genderGroups.Any(g => g.Key==SomeIntFlags.Flag10)); + Assert.That(genderGroups.Any(g => g.Key == SomeIntFlags.None)); + Assert.That(genderGroups.Any(g => g.Key == SomeIntFlags.Flag10)); }; RunTestInSession(testAction); } @@ -351,11 +384,11 @@ public void IndirectGroupByByConditionalOperatorForLongFlagTest() Flags = el.NullableFlags.HasValue ? el.NullableFlags.Value : SomeLongFlags.None }) .GroupBy(x => x.Flags) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==SomeLongFlags.None)); - Assert.That(genderGroups.Any(g => g.Key==SomeLongFlags.Flag10)); + Assert.That(genderGroups.Any(g => g.Key == SomeLongFlags.None)); + Assert.That(genderGroups.Any(g => g.Key == SomeLongFlags.Flag10)); }; RunTestInSession(testAction); } @@ -370,11 +403,11 @@ public void IndirectGroupByByConditionalOperatorForDateTimeTest() DateTime = el.NullableDateTime.HasValue ? el.NullableDateTime.Value : new DateTime(2012, 12, 12) }) .GroupBy(x => x.DateTime) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(genderGroups.Length, Is.EqualTo(2)); - Assert.That(genderGroups.Any(g => g.Key==new DateTime(2012, 12, 12))); - Assert.That(genderGroups.Any(g => g.Key==nullableFieldDateTime)); + Assert.That(genderGroups.Any(g => g.Key == new DateTime(2012, 12, 12))); + Assert.That(genderGroups.Any(g => g.Key == nullableFieldDateTime)); }; RunTestInSession(testAction); } @@ -389,11 +422,11 @@ public void IndirectGroupByByConditionalOperatorForIntTest() NullableInt = el.NullableInt.HasValue ? el.NullableInt : -1 }) .GroupBy(x => x.NullableInt) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==-1)); - Assert.That(result.Any(g => g.Key==10)); + Assert.That(result.Any(g => g.Key == -1)); + Assert.That(result.Any(g => g.Key == 10)); }; RunTestInSession(testAction); } @@ -407,8 +440,8 @@ public void DirectGroupByByCoalescingOperatorForIntEnumTest() .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==Gender.None)); - Assert.That(result.Any(g => g.Key==Gender.Female)); + Assert.That(result.Any(g => g.Key == Gender.None)); + Assert.That(result.Any(g => g.Key == Gender.Female)); }; RunTestInSession(testAction); } @@ -419,11 +452,11 @@ public void DirectGroupByByCoalescingOperatorForLongEnumTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableGender ?? ExtendedGender.None) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==ExtendedGender.None)); - Assert.That(result.Any(g => g.Key==ExtendedGender.Female)); + Assert.That(result.Any(g => g.Key == ExtendedGender.None)); + Assert.That(result.Any(g => g.Key == ExtendedGender.Female)); }; RunTestInSession(testAction); } @@ -434,11 +467,11 @@ public void DirectGroupByByCoalescingOperatorForIntFlagTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableFlags ?? SomeIntFlags.None) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.None)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.None)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.Flag10)); }; RunTestInSession(testAction); } @@ -452,8 +485,8 @@ public void DirectGroupByByCoalescingOperatorForLongFlagTest() .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.None)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.None)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.Flag10)); }; RunTestInSession(testAction); } @@ -464,11 +497,11 @@ public void DirectGroupByByCoalescingOperatorForDateTimeTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableDateTime ?? new DateTime(2012, 12, 12)) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==nullableFieldDateTime)); - Assert.That(result.Any(g => g.Key==new DateTime(2012, 12, 12))); + Assert.That(result.Any(g => g.Key == nullableFieldDateTime)); + Assert.That(result.Any(g => g.Key == new DateTime(2012, 12, 12))); }; RunTestInSession(testAction); } @@ -479,11 +512,11 @@ public void DirectGroupByByCoalescingOperatorForIntTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableInt ?? -1) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==-1)); - Assert.That(result.Any(g => g.Key==10)); + Assert.That(result.Any(g => g.Key == -1)); + Assert.That(result.Any(g => g.Key == 10)); }; RunTestInSession(testAction); } @@ -498,11 +531,11 @@ public void IndirectGroupByByCoalescingOperatorForIntEnumTest() NullableGender = el.NullableGender ?? Gender.None }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==Gender.None)); - Assert.That(result.Any(g => g.Key==Gender.Female)); + Assert.That(result.Any(g => g.Key == Gender.None)); + Assert.That(result.Any(g => g.Key == Gender.Female)); }; RunTestInSession(testAction); } @@ -517,11 +550,11 @@ public void IndirectGroupByByCoalescingOperatorForLongEnumTest() NullableGender = el.NullableGender ?? ExtendedGender.None }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==ExtendedGender.None)); - Assert.That(result.Any(g => g.Key==ExtendedGender.Female)); + Assert.That(result.Any(g => g.Key == ExtendedGender.None)); + Assert.That(result.Any(g => g.Key == ExtendedGender.Female)); }; RunTestInSession(testAction); } @@ -536,11 +569,11 @@ public void IndirectGroupByByCoalescingOperatorForIntFlagTest() NullableGender = el.NullableFlags ?? SomeIntFlags.None }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.None)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.None)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.Flag10)); }; RunTestInSession(testAction); } @@ -555,11 +588,11 @@ public void IndirectGroupByByCoalescingOperatorForLongFlagTest() NullableGender = el.NullableFlags ?? SomeLongFlags.None }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.None)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.None)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.Flag10)); }; RunTestInSession(testAction); } @@ -574,11 +607,11 @@ public void IndirectGroupByByCoalescingOperatorForDateTimeTest() NullableGender = el.NullableDateTime ?? new DateTime(2012, 12, 12) }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==new DateTime(2012, 12, 12))); - Assert.That(result.Any(g => g.Key==nullableFieldDateTime)); + Assert.That(result.Any(g => g.Key == new DateTime(2012, 12, 12))); + Assert.That(result.Any(g => g.Key == nullableFieldDateTime)); }; RunTestInSession(testAction); } @@ -593,11 +626,11 @@ public void IndirectGroupByByCoalescingOperatorForIntTest() NullableInt = el.NullableInt ?? -1 }) .GroupBy(x => x.NullableInt) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==-1)); - Assert.That(result.Any(g => g.Key==10)); + Assert.That(result.Any(g => g.Key == -1)); + Assert.That(result.Any(g => g.Key == 10)); }; RunTestInSession(testAction); } @@ -608,11 +641,11 @@ public void DirectGroupByByGetValueOrDefaultForIntEnumTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableGender.GetValueOrDefault(Gender.None)) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==Gender.None)); - Assert.That(result.Any(g => g.Key==Gender.Female)); + Assert.That(result.Any(g => g.Key == Gender.None)); + Assert.That(result.Any(g => g.Key == Gender.Female)); }; RunTestInSession(testAction); } @@ -623,11 +656,11 @@ public void DirectGroupByByGetValueOrDefaultForLongEnumTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableGender.GetValueOrDefault(ExtendedGender.None)) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==ExtendedGender.None)); - Assert.That(result.Any(g => g.Key==ExtendedGender.Female)); + Assert.That(result.Any(g => g.Key == ExtendedGender.None)); + Assert.That(result.Any(g => g.Key == ExtendedGender.Female)); }; RunTestInSession(testAction); } @@ -641,8 +674,8 @@ public void DirectGroupByGetValueOrDefaultForIntFlagTest() .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.None)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.None)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.Flag10)); }; RunTestInSession(testAction); } @@ -653,11 +686,11 @@ public void DirectGroupByByGetValueOrDefaultForLongFlagTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableFlags.GetValueOrDefault(SomeLongFlags.None)) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.None)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.None)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.Flag10)); }; RunTestInSession(testAction); } @@ -668,11 +701,11 @@ public void DirectGroupByByGetValueOrDefaultForDateTimeTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableDateTime.GetValueOrDefault(new DateTime(2012, 12, 12))) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==new DateTime(2012, 12, 12))); - Assert.That(result.Any(g => g.Key==nullableFieldDateTime)); + Assert.That(result.Any(g => g.Key == new DateTime(2012, 12, 12))); + Assert.That(result.Any(g => g.Key == nullableFieldDateTime)); }; RunTestInSession(testAction); } @@ -683,11 +716,11 @@ public void DirectGroupByByGetValueOrDefaultForIntTest() Action testAction = (session) => { var result = session.Query.All() .GroupBy(x => x.NullableInt.GetValueOrDefault(-1)) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==-1)); - Assert.That(result.Any(g => g.Key==10)); + Assert.That(result.Any(g => g.Key == -1)); + Assert.That(result.Any(g => g.Key == 10)); }; RunTestInSession(testAction); } @@ -702,11 +735,11 @@ public void IndirectGroupByByGetValueOrDefaultForIntEnumTest() NullableGender = el.NullableGender.GetValueOrDefault(Gender.None) }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==Gender.None)); - Assert.That(result.Any(g => g.Key==Gender.Female)); + Assert.That(result.Any(g => g.Key == Gender.None)); + Assert.That(result.Any(g => g.Key == Gender.Female)); }; RunTestInSession(testAction); } @@ -721,11 +754,11 @@ public void IndirectGroupByByGetValueOrDefaultForLongEnumTest() NullableGender = el.NullableGender.GetValueOrDefault(ExtendedGender.None) }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==ExtendedGender.None)); - Assert.That(result.Any(g => g.Key==ExtendedGender.Female)); + Assert.That(result.Any(g => g.Key == ExtendedGender.None)); + Assert.That(result.Any(g => g.Key == ExtendedGender.Female)); }; RunTestInSession(testAction); } @@ -740,11 +773,11 @@ public void IndirectGroupByByGetValueOrDefaultForFlagTest() NullableGender = el.NullableFlags.GetValueOrDefault(SomeIntFlags.None) }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.None)); - Assert.That(result.Any(g => g.Key==SomeIntFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.None)); + Assert.That(result.Any(g => g.Key == SomeIntFlags.Flag10)); }; RunTestInSession(testAction); } @@ -759,11 +792,11 @@ public void IndirectGroupByByGetValueOrDefaultForLongFlagTest() NullableGender = el.NullableFlags.GetValueOrDefault(SomeLongFlags.None) }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.None)); - Assert.That(result.Any(g => g.Key==SomeLongFlags.Flag10)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.None)); + Assert.That(result.Any(g => g.Key == SomeLongFlags.Flag10)); }; RunTestInSession(testAction); } @@ -778,11 +811,11 @@ public void IndirectGroupByByGetValueOrDefaultForDateTimeTest() NullableGender = el.NullableDateTime.GetValueOrDefault(new DateTime(2012, 12, 12)) }) .GroupBy(x => x.NullableGender) - .Select(g => new {Key = g.Key, Items = g}) + .Select(g => new { Key = g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==new DateTime(2012, 12, 12))); - Assert.That(result.Any(g => g.Key==nullableFieldDateTime)); + Assert.That(result.Any(g => g.Key == new DateTime(2012, 12, 12))); + Assert.That(result.Any(g => g.Key == nullableFieldDateTime)); }; RunTestInSession(testAction); } @@ -797,11 +830,11 @@ public void IndirectGroupByByGetValueOrDefaultForIntTest() NullableInt = el.NullableInt.GetValueOrDefault(-1) }) .GroupBy(x => x.NullableInt) - .Select(g => new {g.Key, Items = g}) + .Select(g => new { g.Key, Items = g }) .ToArray(); Assert.That(result.Length, Is.EqualTo(2)); - Assert.That(result.Any(g => g.Key==-1)); - Assert.That(result.Any(g => g.Key==10)); + Assert.That(result.Any(g => g.Key == -1)); + Assert.That(result.Any(g => g.Key == 10)); }; RunTestInSession(testAction); } @@ -823,9 +856,9 @@ public void OrderByBitAndExpressionTest() { Action testAction = (session) => { var result1 = session.Query.All() - .OrderBy(el => (el.Flags & SomeIntFlags.Flag1)==SomeIntFlags.Flag1).ToArray(); + .OrderBy(el => (el.Flags & SomeIntFlags.Flag1) == SomeIntFlags.Flag1).ToArray(); var result2 = session.Query.All() - .OrderBy(el => (el.Flags & SomeLongFlags.Flag1)==SomeLongFlags.Flag1).ToArray(); + .OrderBy(el => (el.Flags & SomeLongFlags.Flag1) == SomeLongFlags.Flag1).ToArray(); }; RunTestInSession(testAction); } @@ -851,24 +884,24 @@ public void OrderByInequalityExpressionTest() { Action testAction = (session) => { var result1 = session.Query.All() - .OrderBy(el => el.Gender!=Gender.Male).ToArray(); + .OrderBy(el => el.Gender != Gender.Male).ToArray(); var result2 = session.Query.All() - .OrderBy(el => Gender.Male!=el.Gender).ToArray(); + .OrderBy(el => Gender.Male != el.Gender).ToArray(); var result3 = session.Query.All() - .OrderBy(el => el.Gender!=ExtendedGender.Male).ToArray(); + .OrderBy(el => el.Gender != ExtendedGender.Male).ToArray(); var result4 = session.Query.All() - .OrderBy(el => ExtendedGender.Male!=el.Gender).ToArray(); + .OrderBy(el => ExtendedGender.Male != el.Gender).ToArray(); var result5 = session.Query.All() - .OrderBy(el => el.Flags!=SomeIntFlags.Flag1).ToArray(); + .OrderBy(el => el.Flags != SomeIntFlags.Flag1).ToArray(); var result6 = session.Query.All() - .OrderBy(el => SomeIntFlags.Flag1!=el.Flags).ToArray(); + .OrderBy(el => SomeIntFlags.Flag1 != el.Flags).ToArray(); var result7 = session.Query.All() - .OrderBy(el => el.Flags!=SomeLongFlags.Flag1).ToArray(); + .OrderBy(el => el.Flags != SomeLongFlags.Flag1).ToArray(); var result8 = session.Query.All() - .OrderBy(el => SomeLongFlags.Flag1!=el.Flags).ToArray(); + .OrderBy(el => SomeLongFlags.Flag1 != el.Flags).ToArray(); }; RunTestInSession(testAction); } @@ -878,24 +911,24 @@ public void OrderByEqualityExpression() { Action testAction = (session) => { var result1 = session.Query.All() - .OrderBy(el => el.Gender==Gender.Male).ToArray(); + .OrderBy(el => el.Gender == Gender.Male).ToArray(); var result2 = session.Query.All() - .OrderBy(el => Gender.Male==el.Gender).ToArray(); + .OrderBy(el => Gender.Male == el.Gender).ToArray(); var result3 = session.Query.All() - .OrderBy(el => el.Gender==ExtendedGender.Male).ToArray(); + .OrderBy(el => el.Gender == ExtendedGender.Male).ToArray(); var result4 = session.Query.All() - .OrderBy(el => ExtendedGender.Male==el.Gender).ToArray(); + .OrderBy(el => ExtendedGender.Male == el.Gender).ToArray(); var result5 = session.Query.All() - .OrderBy(el => el.Flags==SomeIntFlags.Flag1).ToArray(); + .OrderBy(el => el.Flags == SomeIntFlags.Flag1).ToArray(); var result6 = session.Query.All() - .OrderBy(el => SomeIntFlags.Flag1==el.Flags).ToArray(); + .OrderBy(el => SomeIntFlags.Flag1 == el.Flags).ToArray(); var result7 = session.Query.All() - .OrderBy(el => el.Flags==SomeLongFlags.Flag1).ToArray(); + .OrderBy(el => el.Flags == SomeLongFlags.Flag1).ToArray(); var result8 = session.Query.All() - .OrderBy(el => SomeLongFlags.Flag1==el.Flags).ToArray(); + .OrderBy(el => SomeLongFlags.Flag1 == el.Flags).ToArray(); }; RunTestInSession(testAction); } @@ -917,10 +950,10 @@ public void WhereByBitAndExpressionTest() { Action testAction = (session) => { var result1 = session.Query.All() - .Where(el => (el.Flags & SomeIntFlags.Flag1)==SomeIntFlags.Flag1).ToArray(); + .Where(el => (el.Flags & SomeIntFlags.Flag1) == SomeIntFlags.Flag1).ToArray(); var result2 = session.Query.All() - .Where(el => (el.Flags & SomeLongFlags.Flag1)==SomeLongFlags.Flag1).ToArray(); + .Where(el => (el.Flags & SomeLongFlags.Flag1) == SomeLongFlags.Flag1).ToArray(); }; RunTestInSession(testAction); } @@ -930,24 +963,24 @@ public void WhereByEqualityTest() { Action testAction = (session) => { var result1 = session.Query.All() - .Where(el => el.Gender==Gender.Male).ToArray(); + .Where(el => el.Gender == Gender.Male).ToArray(); var result2 = session.Query.All() - .Where(el => Gender.Male==el.Gender).ToArray(); + .Where(el => Gender.Male == el.Gender).ToArray(); var result3 = session.Query.All() - .Where(el => el.Gender==ExtendedGender.Male).ToArray(); + .Where(el => el.Gender == ExtendedGender.Male).ToArray(); var result4 = session.Query.All() - .Where(el => ExtendedGender.Male==el.Gender).ToArray(); + .Where(el => ExtendedGender.Male == el.Gender).ToArray(); var result5 = session.Query.All() - .Where(el => el.Flags==SomeIntFlags.Flag1).ToArray(); + .Where(el => el.Flags == SomeIntFlags.Flag1).ToArray(); var result6 = session.Query.All() - .Where(el => SomeIntFlags.Flag1==el.Flags).ToArray(); + .Where(el => SomeIntFlags.Flag1 == el.Flags).ToArray(); var result7 = session.Query.All() - .Where(el => el.Flags==SomeLongFlags.Flag1).ToArray(); + .Where(el => el.Flags == SomeLongFlags.Flag1).ToArray(); var result8 = session.Query.All() - .Where(el => SomeLongFlags.Flag1==el.Flags).ToArray(); + .Where(el => SomeLongFlags.Flag1 == el.Flags).ToArray(); }; RunTestInSession(testAction); } @@ -957,24 +990,24 @@ public void WhereByInequalityTest() { Action testAction = (session) => { var result1 = session.Query.All() - .Where(el => el.Gender!=Gender.Female).ToArray(); + .Where(el => el.Gender != Gender.Female).ToArray(); var result2 = session.Query.All() - .Where(el => Gender.Female!=el.Gender).ToArray(); + .Where(el => Gender.Female != el.Gender).ToArray(); var result3 = session.Query.All() - .Where(el => el.Gender!=ExtendedGender.Female).ToArray(); + .Where(el => el.Gender != ExtendedGender.Female).ToArray(); var result4 = session.Query.All() - .Where(el => ExtendedGender.Female!=el.Gender).ToArray(); + .Where(el => ExtendedGender.Female != el.Gender).ToArray(); var result5 = session.Query.All() - .Where(el => el.Flags!=SomeIntFlags.Flag1).ToArray(); + .Where(el => el.Flags != SomeIntFlags.Flag1).ToArray(); var result6 = session.Query.All() - .Where(el => SomeIntFlags.Flag1!=el.Flags).ToArray(); + .Where(el => SomeIntFlags.Flag1 != el.Flags).ToArray(); var result7 = session.Query.All() - .Where(el => el.Flags!=SomeLongFlags.Flag1).ToArray(); + .Where(el => el.Flags != SomeLongFlags.Flag1).ToArray(); var result8 = session.Query.All() - .Where(el => SomeLongFlags.Flag1!=el.Flags).ToArray(); + .Where(el => SomeLongFlags.Flag1 != el.Flags).ToArray(); }; RunTestInSession(testAction); } @@ -982,15 +1015,93 @@ public void WhereByInequalityTest() [Test] public void MathRoundTest() { + Require.ProviderIsNot(StorageProvider.Sqlite); + + Action testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .Select(e => (Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100)).ToArray()); + }; + RunTestInSession(testAction); + testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .Where(e => (Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100) > 1).ToArray()); + }; + RunTestInSession(testAction); + testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .OrderBy(e => Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100).ToArray()); + }; + RunTestInSession(testAction); + testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .Sum(e => Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100)); + }; + RunTestInSession(testAction); + testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .Select(e => (Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100)) + .ToArray()); + }; + RunTestInSession(testAction); + testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .Where(e => (Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100) > 1) + .ToArray()); + }; + RunTestInSession(testAction); + testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .OrderBy(e => Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100) + .ToArray()); + }; + RunTestInSession(testAction); + testAction = (session) => { + Assert.DoesNotThrow(() => session.Query.All() + .Sum(e => Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100)); + }; + RunTestInSession(testAction); + } + + [Test] + public void MathRoundSqliteTest() + { + Require.ProviderIs(StorageProvider.Sqlite); + Action testAction = (session) => { - Assert.DoesNotThrow(() => session.Query.All().Select(e => (Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100)).ToArray()); - Assert.DoesNotThrow(() => session.Query.All().Where(e => (Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100) > 1).ToArray()); - Assert.DoesNotThrow(() => session.Query.All().OrderBy(e => Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100).ToArray()); - Assert.DoesNotThrow(() => session.Query.All().Sum(e => Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100)); - Assert.DoesNotThrow(() => session.Query.All().Select(e => (Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100)).ToArray()); - Assert.DoesNotThrow(() => session.Query.All().Where(e => (Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100) > 1).ToArray()); - Assert.DoesNotThrow(() => session.Query.All().OrderBy(e => Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100).ToArray()); - Assert.DoesNotThrow(() => session.Query.All().Sum(e => Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100)); + _ = Assert.Throws(() => session.Query.All() + .Where(e => (Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100) > 1).ToArray()); + }; + RunTestInSession(testAction); + + testAction = (session) => { + _ = Assert.Throws(() => session.Query.All() + .OrderBy(e => Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100).ToArray()); + }; + RunTestInSession(testAction); + + testAction = (session) => { + _= Assert.Throws(() => session.Query.All() + .Sum(e => Math.Truncate(Math.Round(e.Sum, 2) * 100) / 100)); + }; + RunTestInSession(testAction); + + testAction = (session) => { + _ = Assert.Throws(() => session.Query.All() + .Where(e => (Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100) > 1) + .ToArray()); + }; + RunTestInSession(testAction); + + testAction = (session) => { + _ =Assert.Throws(() => session.Query.All() + .OrderBy(e => Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100) + .ToArray()); + }; + RunTestInSession(testAction); + + testAction = (session) => { + _ = Assert.Throws(() => session.Query.All() + .Sum(e => Math.Truncate(Math.Round(e.Sum, 2, MidpointRounding.AwayFromZero) * 100) / 100)); }; RunTestInSession(testAction); } @@ -1000,8 +1111,8 @@ public void ConcatinationTest() { Action testAction = session => { Assert.DoesNotThrow( - () => session.Query.All().Select(q=> new {q.Id, Gender = Gender.Female}) - .Concat(session.Query.All().Select(q=> new {q.Id, Gender = Gender.Male})) + () => session.Query.All().Select(q => new { q.Id, Gender = Gender.Female }) + .Concat(session.Query.All().Select(q => new { q.Id, Gender = Gender.Male })) .FirstOrDefault()); }; RunTestInSession(testAction); @@ -1014,37 +1125,5 @@ private void RunTestInSession(Action testBody) testBody.Invoke(session); } } - - protected override void PopulateData() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new EntityWithGender {Gender = Gender.Male}; - new EntityWithGender {Gender = Gender.Female, NullableGender = Gender.Female}; - - new EntityWithExtendedGender {Gender = ExtendedGender.Male}; - new EntityWithExtendedGender {Gender = ExtendedGender.Female, NullableGender = ExtendedGender.Female}; - - new EntityWithIntFlags {Flags = SomeIntFlags.Flag1 | SomeIntFlags.Flag20}; - new EntityWithIntFlags {Flags = SomeIntFlags.Flag1 | SomeIntFlags.Flag10, NullableFlags = SomeIntFlags.Flag10}; - - new EntityWithLongFlags {Flags = SomeLongFlags.Flag1 | SomeLongFlags.Flag20}; - new EntityWithLongFlags {Flags = SomeLongFlags.Flag1 | SomeLongFlags.Flag20, NullableFlags = SomeLongFlags.Flag10}; - - new EntityWithDateTime {DateTime = firstDateTime}; - new EntityWithDateTime {DateTime = secondDateTime, NullableDateTime = nullableFieldDateTime}; - - new EntityWithInt {Int = 20}; - new EntityWithInt {Int = 20, NullableInt = 10}; - transaction.Complete(); - } - } - - protected override DomainConfiguration BuildConfiguration() { - var configuration = base.BuildConfiguration(); - configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (EntityWithGender).Assembly, typeof (EntityWithGender).Namespace); - return configuration; - } } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/ConstraintsTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ConstraintsTest.cs index 45832ec73c..4ecaa521ed 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ConstraintsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ConstraintsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2008.08.18 @@ -16,14 +16,15 @@ public class ConstraintsTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); - config.Types.Register(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Storage.BookAuthorModel"); + var config = base.BuildConfiguration(); + config.Types.Register(Assembly.GetExecutingAssembly(), typeof(Book).Namespace); return config; } [Test] public void NotNullableViolationTest() { + Require.ProviderIsNot(StorageProvider.Sqlite);// no column length supported so no exception thrown using (var session = Domain.OpenSession()) { using (session.OpenTransaction()) { var book = new Book(); @@ -45,10 +46,10 @@ public void SessionBoundaryViolationTest() { using (var session = Domain.OpenSession()) { using (session.OpenTransaction()) { - Author author = new Author(); + var author = new Author(); using (var session2 = Domain.OpenSession()) { using (session2.OpenTransaction()) { - Book book = new Book(); + var book = new Book(); // Author is bound to another session AssertEx.ThrowsInvalidOperationException(() => book.Author = author); diff --git a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs index 9d679ea0e2..b9a8dd1ada 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2013.08.16 @@ -266,19 +266,25 @@ public class IgnoreRulesValidateTest { private SqlDriver sqlDriver; private Key changedOrderKey; + private bool createConstraintsWithTable; private bool isMultidatabaseTest; private bool isMultischemaTest; [OneTimeSetUp] - public void Setup() + public void OneTimeSetUp() { sqlDriver = TestSqlDriver.Create(GetConnectionInfo()); + if(StorageProviderInfo.Instance.Provider == StorageProvider.Sqlite) { + createConstraintsWithTable = true; + } } + [SetUp] + public void SetUp() => ClearMultidatabaseAndMultischemaFlags(); + [Test] public void PerformUpdateTest() { - ClearMultidatabaseAndMultischemaFlags(); BuildDomainAndFillData(); UpgradeDomain(DomainUpgradeMode.Perform); BuildDomainInValidateMode(); @@ -287,7 +293,6 @@ public void PerformUpdateTest() [Test] public void PerformSafelyUpdateTest() { - ClearMultidatabaseAndMultischemaFlags(); BuildDomainAndFillData(); UpgradeDomain(DomainUpgradeMode.PerformSafely); BuildDomainInValidateMode(); @@ -296,89 +301,102 @@ public void PerformSafelyUpdateTest() [Test] public void IgnoreSimpleColumnTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.VarChar, 25)); - IgnoreRuleCollection ignoreRuleCollection = new IgnoreRuleCollection(); - ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); - var validatedDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof (Model3.MyEntity1)); - validatedDomain.Dispose(); + CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.Int32)); + var ignoreRuleCollection = new IgnoreRuleCollection(); + _ = ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); + + BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof(Model3.MyEntity1)).Dispose(); } [Test] public void IgnoreReferencedColumnTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); + Require.AllFeaturesSupported(ProviderFeatures.ForeignKeyConstraints); + + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; CreateColumn(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKey(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity1_MyEntity1ID"); + CreateForeignKeyInDb(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity1_MyEntity1ID"); var ignoreRuleCollection = new IgnoreRuleCollection(); - ignoreRuleCollection.IgnoreColumn("ReferencedIgnoredColumn").WhenTable("MyEntity2").WhenSchema(schema); - var validatedDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof (Model3.MyEntity1)); - validatedDomain.Dispose(); + _ = ignoreRuleCollection.IgnoreColumn("ReferencedIgnoredColumn").WhenTable("MyEntity2").WhenSchema(schema); + + BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof(Model3.MyEntity1)).Dispose(); } [Test] public void IgnoreSimpleTableTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); - Catalog catalog = GetCatalog(); + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - var addedColumnsNames = new[] {"Id", "FirstColumn"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar, 25)}; - CreateTable(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); + var addedColumnsNames = new[] { "Id", "FirstColumn" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64) }; + + if (createConstraintsWithTable) { + var delayedOp = CreateTableDelayed(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyLocally(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); + delayedOp(); + } + else { + CreateTable(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); + } var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreTable("MyIgnoredEntity"); - var validateDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof (Model3.MyEntity1)); - validateDomain.Dispose(); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity"); + + BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof(Model3.MyEntity1)).Dispose(); } [Test] public void IgnoreReferencedTableTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); - Catalog catalog = GetCatalog(); + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - var addedColumnsNames = new[] {"Id", "FirstColumn", "MyEntity2Id"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.Int64)}; - CreateTable(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); - CreateForeignKey(catalog, schema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + + if (createConstraintsWithTable) { + var delayedOp = CreateTableDelayed(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyLocally(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); + CreateForeignKeyLocally(catalog, schema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + delayedOp(); + } + else { + CreateTable(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); + CreateForeignKeyInDb(catalog, schema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + } + var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreTable("MyIgnoredEntity"); - var validateDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof (Model3.MyEntity1)); - validateDomain.Dispose(); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity"); + + BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof(Model3.MyEntity1)).Dispose(); } [Test] public void InsertIntoTableWithIgnoredColumnTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); - Catalog catalog = GetCatalog(); + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "Myentity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.VarChar, 25)); - IgnoreRuleCollection ignoreRuleCollection = new IgnoreRuleCollection(); - ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); - using (var validatedDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof (Model3.MyEntity1))) + CreateColumn(catalog, schema, "Myentity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.Int64)); + var ignoreRuleCollection = new IgnoreRuleCollection(); + _ = ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); + + using (var validatedDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof(Model3.MyEntity1))) using (var session = validatedDomain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new Model3.MyEntity2 {FirstColumn = "some test"}; + _ = new Model3.MyEntity2 { FirstColumn = "some test" }; transaction.Complete(); } ValidateMyEntity(catalog, schema); @@ -387,27 +405,28 @@ public void InsertIntoTableWithIgnoredColumnTest() [Test] public void InsertIntoTableWithNotNullableIgnoredColumnTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); + Require.ProviderIsNot(StorageProvider.Sqlite); - Catalog catalog = GetCatalog(); - var schema = catalog.Schemas[catalog.DefaultSchema.Name]; - if (schema==null) - schema = catalog.Schemas[0]; + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); - schema.Tables["MyEntity2"].CreateColumn("SimpleIgnoredColumn", new SqlValueType(SqlType.VarChar, 30)).IsNullable = false; - SqlAlterTable alter = SqlDdl.Alter(schema.Tables["MyEntity2"], + var catalog = GetCatalog(); + var schema = catalog.Schemas[catalog.DefaultSchema.Name] ?? catalog.Schemas[0]; + + schema.Tables["MyEntity2"].CreateColumn("SimpleIgnoredColumn", new SqlValueType(SqlType.Int64)).IsNullable = false; + + var alter = SqlDdl.Alter(schema.Tables["MyEntity2"], SqlDdl.AddColumn(schema.Tables["MyEntity2"].TableColumns["SimpleIgnoredColumn"])); var commandText = sqlDriver.Compile(alter).GetCommandText(); ExecuteNonQuery(commandText); - IgnoreRuleCollection ignoreRuleCollection = new IgnoreRuleCollection(); - ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2").WhenSchema(schema.Name); - Assert.Throws(Is.InstanceOf(typeof (StorageException)), () => { - using (var validatedDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof (Model3.MyEntity1))) + + var ignoreRuleCollection = new IgnoreRuleCollection(); + _ = ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2").WhenSchema(schema.Name); + + _ = Assert.Throws(Is.InstanceOf(typeof(StorageException)), () => { + using (var validatedDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRuleCollection, typeof(Model3.MyEntity1))) using (var session = validatedDomain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new Model3.MyEntity2 {FirstColumn = "some test"}; + _ = new Model3.MyEntity2 { FirstColumn = "some test" }; transaction.Complete(); } }); @@ -416,118 +435,136 @@ public void InsertIntoTableWithNotNullableIgnoredColumnTest() [Test] public void DropTableWithIgnoredColumnTest() { - ClearMultidatabaseAndMultischemaFlags(); - Assert.Throws(() => { - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); - var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.VarChar, 25)); - IgnoreRuleCollection ignoreRuleCollection = new IgnoreRuleCollection(); - ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); - var performDomain = - BuildSimpleDomain(DomainUpgradeMode.Perform, ignoreRuleCollection, typeof (Model4.MyEntity1)); - performDomain.Dispose(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); + var schema = catalog.DefaultSchema.Name; + CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.Int64)); + + var ignoreRuleCollection = new IgnoreRuleCollection(); + _ = ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); + + _ = Assert.Throws(() => { + BuildSimpleDomain(DomainUpgradeMode.Perform, ignoreRuleCollection, typeof(Model4.MyEntity1)).Dispose(); }); } [Test] public void DropReferencedTableTest() { - ClearMultidatabaseAndMultischemaFlags(); - Assert.Throws(() => { - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); - var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKey(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", - "FK_MyEntity1_MyEntity1ID"); - var ignoreRuleCollection = new IgnoreRuleCollection(); - ignoreRuleCollection.IgnoreColumn("ReferencedIgnoredColumn").WhenTable("MyEntity2").WhenSchema(schema); - var performDomain = - BuildSimpleDomain(DomainUpgradeMode.Perform, ignoreRuleCollection, typeof (Model4.MyEntity1)); - performDomain.Dispose(); + Require.AllFeaturesSupported(ProviderFeatures.ForeignKeyConstraints); + + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); + var schema = catalog.DefaultSchema.Name; + CreateColumn(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateForeignKeyInDb(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity1_MyEntity1ID"); + + var ignoreRuleCollection = new IgnoreRuleCollection(); + _ = ignoreRuleCollection.IgnoreColumn("ReferencedIgnoredColumn").WhenTable("MyEntity2").WhenSchema(schema); + + _ = Assert.Throws(() => { + BuildSimpleDomain(DomainUpgradeMode.Perform, ignoreRuleCollection, typeof(Model4.MyEntity1)).Dispose(); }); } [Test] public void IgnoreColumnsByMaskValidateTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "IgnoreFirstColumn", new SqlValueType(SqlType.VarChar, 25)); - CreateColumn(catalog, schema, "MyEntity2", "IgnoreSecondColumn", new SqlValueType(SqlType.VarChar, 25)); - CreateColumn(catalog, schema, "MyEntity2", "IgnoreThirdColumn", new SqlValueType(SqlType.VarChar, 25)); + CreateColumn(catalog, schema, "MyEntity2", "IgnoreFirstColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "IgnoreSecondColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "IgnoreThirdColumn", new SqlValueType(SqlType.Int64)); var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("Ignore*"); - var validateDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof (Model3.MyEntity1)); - validateDomain.Dispose(); + _ = ignoreRules.IgnoreColumn("Ignore*"); + + BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof(Model3.MyEntity1)).Dispose(); } [Test] public void IgnoreTablesByMaskValidateTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - var addedColumnsNames = new[] {"Id", "FirstColumn", "SecondColumn"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.VarChar, 25)}; - CreateTable(catalog, schema, "IgnoredFirstTable", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, schema, "IgnoredFirstTable", "Id", "PK_IgnoredFirstTable_Id"); - CreateTable(catalog, schema, "IgnoredSecondTable", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, schema, "IgnoredSecondTable", "Id", "PK_IgnoredSecondTable_Id"); + var addedColumnsNames = new[] { "Id", "FirstColumn", "SecondColumn" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + + if (createConstraintsWithTable) { + var delayedOp = CreateTableDelayed(catalog, schema, "IgnoredFirstTable", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyLocally(catalog, schema, "IgnoredFirstTable", "Id", "PK_IgnoredFirstTable_Id"); + delayedOp(); + + delayedOp = CreateTableDelayed(catalog, schema, "IgnoredSecondTable", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyLocally(catalog, schema, "IgnoredSecondTable", "Id", "PK_IgnoredSecondTable_Id"); + delayedOp(); + } + else { + CreateTable(catalog, schema, "IgnoredFirstTable", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, schema, "IgnoredFirstTable", "Id", "PK_IgnoredFirstTable_Id"); + + CreateTable(catalog, schema, "IgnoredSecondTable", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, schema, "IgnoredSecondTable", "Id", "PK_IgnoredSecondTable_Id"); + } var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreTable("Ignored*"); - var validateDomain = BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof (Model3.MyEntity1)); - validateDomain.Dispose(); + _ = ignoreRules.IgnoreTable("Ignored*"); + + BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof(Model3.MyEntity1)).Dispose(); } [Test] public void IgnoreAllColumnsInTableByMaskValidateTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - var addedColumnsNames = new[] {"Id", "FirstColumn", "SecondColumn"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.VarChar, 25)}; - CreateTable(catalog, schema, "IgnoredTable", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, schema, "IgnoredTable", "Id", "PK_IgnoredTable_Id"); + var addedColumnsNames = new[] { "Id", "FirstColumn", "SecondColumn" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + + if (createConstraintsWithTable) { + var delayedOp = CreateTableDelayed(catalog, schema, "IgnoredTable", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyLocally(catalog, schema, "IgnoredTable", "Id", "PK_IgnoredTable_Id"); + delayedOp(); + } + else { + CreateTable(catalog, schema, "IgnoredTable", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, schema, "IgnoredTable", "Id", "PK_IgnoredTable_Id"); + } var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("*").WhenTable("IgnoredTable"); - BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof (Model3.MyEntity1)).Dispose(); + _ = ignoreRules.IgnoreColumn("*").WhenTable("IgnoredTable"); + + BuildSimpleDomain(DomainUpgradeMode.Validate, ignoreRules, typeof(Model3.MyEntity1)).Dispose(); } [Test] public void UpgradeDomainWithIgnoreRuleByMaskInPerformModeTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); - var schema = catalog.Schemas[catalog.DefaultSchema.Name]; - if (schema==null) - schema = catalog.Schemas[0]; - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", new SqlValueType(SqlType.VarChar, 25)); - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", new SqlValueType(SqlType.VarChar, 25)); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); + var schema = catalog.Schemas[catalog.DefaultSchema.Name] ?? catalog.Schemas[0]; + + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", new SqlValueType(SqlType.Int64)); + var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("Ignored*").WhenTable("MyEntity2"); - using (var domain = BuildSimpleDomain(DomainUpgradeMode.Perform, ignoreRules, typeof (Model3.MyEntity1))) + _ = ignoreRules.IgnoreColumn("Ignored*").WhenTable("MyEntity2"); + + using (var domain = BuildSimpleDomain(DomainUpgradeMode.Perform, ignoreRules, typeof(Model3.MyEntity1))) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new Model3.MyEntity1 {FirstColumn = "Some text"}; - new Model3.MyEntity2 {FirstColumn = "Second some test"}; + _ = new Model3.MyEntity1 { FirstColumn = "Some text" }; + _ = new Model3.MyEntity2 { FirstColumn = "Second some test" }; transaction.Complete(); } - SqlTableRef myEntity2 = SqlDml.TableRef(schema.Tables["MyEntity2"]); - SqlSelect select = SqlDml.Select(myEntity2); + var myEntity2 = SqlDml.TableRef(schema.Tables["MyEntity2"]); + var select = SqlDml.Select(myEntity2); var compileConfiguration = new SqlCompilerConfiguration(); compileConfiguration.DatabaseQualifiedObjects = false; var commandText = sqlDriver.Compile(select, compileConfiguration).GetCommandText(); @@ -538,26 +575,25 @@ public void UpgradeDomainWithIgnoreRuleByMaskInPerformModeTest() [Test] public void UpgradeDomainWithIgnoreRuleByMaskInPerformSafelyModeTest() { - ClearMultidatabaseAndMultischemaFlags(); - var initialDomain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model3.MyEntity1)); - initialDomain.Dispose(); - Catalog catalog = GetCatalog(); - var schema = catalog.Schemas[catalog.DefaultSchema.Name]; - if (schema==null) - schema = catalog.Schemas[0]; - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", new SqlValueType(SqlType.VarChar, 25)); - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", new SqlValueType(SqlType.VarChar, 25)); + BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); + + var catalog = GetCatalog(); + var schema = catalog.Schemas[catalog.DefaultSchema.Name] ?? catalog.Schemas[0]; + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", new SqlValueType(SqlType.Int64)); + var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("Ignored*"); - using (var domain = BuildSimpleDomain(DomainUpgradeMode.PerformSafely, ignoreRules, typeof (Model3.MyEntity1))) + _ = ignoreRules.IgnoreColumn("Ignored*"); + + using (var domain = BuildSimpleDomain(DomainUpgradeMode.PerformSafely, ignoreRules, typeof(Model3.MyEntity1))) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new Model3.MyEntity1 {FirstColumn = "Some text"}; - new Model3.MyEntity2 {FirstColumn = "Second some test"}; + _ = new Model3.MyEntity1 { FirstColumn = "Some text" }; + _ = new Model3.MyEntity2 { FirstColumn = "Second some test" }; transaction.Complete(); } - SqlTableRef myEntity2 = SqlDml.TableRef(schema.Tables["MyEntity2"]); - SqlSelect select = SqlDml.Select(myEntity2); + var myEntity2 = SqlDml.TableRef(schema.Tables["MyEntity2"]); + var select = SqlDml.Select(myEntity2); var compileConfiguration = new SqlCompilerConfiguration(); compileConfiguration.DatabaseQualifiedObjects = false; var commandText = sqlDriver.Compile(select, compileConfiguration).GetCommandText(); @@ -568,66 +604,72 @@ public void UpgradeDomainWithIgnoreRuleByMaskInPerformSafelyModeTest() [Test] public void MultischemaValidateTest() { - SetMultischema(); Require.AllFeaturesSupported(ProviderFeatures.Multischema | ProviderFeatures.Multidatabase); + + SetMultischema(); + var catalog = GetCatalog(); CreateSchema(catalog, "Model1"); CreateSchema(catalog, "Model2"); - var initialDomain = BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] {typeof(Model1.Customer)}, new[] {typeof(Model3.MyEntity1)}); - initialDomain.Dispose(); + + BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); + catalog = GetCatalog(); CreateColumn(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKey(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + CreateForeignKeyInDb(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; CreateTable(catalog, "Model2", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKey(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreatePrimaryKeyInDb(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); + CreateForeignKeyInDb(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); - ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); - ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); - ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); - - var validateDomain = BuildComplexDomain(DomainUpgradeMode.Validate, ignoreRules, new[] {typeof(Model1.Customer)}, new[] {typeof(Model3.MyEntity1)}); - validateDomain.Dispose(); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); + + BuildComplexDomain(DomainUpgradeMode.Validate, ignoreRules, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); } [Test] public void MultidatabaseValidateTest() { - SetMultidatabase(); Require.AllFeaturesSupported(ProviderFeatures.Multidatabase); - isMultidatabaseTest = true; - var initialDomain = BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] {typeof(Model1.Customer)}, new[] {typeof(Model3.MyEntity1)}); - initialDomain.Dispose(); + + SetMultidatabase(); + + BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); + var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); CreateColumn(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); - CreateForeignKey(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); + CreateForeignKeyInDb(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); + var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; CreateTable(secondCatalog, "dbo", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); - CreatePrimaryKey(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); - CreateForeignKey(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); + CreatePrimaryKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); + CreateForeignKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); + var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("dbo").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("IgnoredTable").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); - ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); - ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); - - var validateDomain = BuildComplexDomain(DomainUpgradeMode.Validate, ignoreRules, new[] { typeof (Model1.Customer) }, new[] { typeof (Model3.MyEntity1) }); - validateDomain.Dispose(); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("dbo").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + + BuildComplexDomain(DomainUpgradeMode.Validate, ignoreRules, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); } [Test] public void MultischemaUpgrageInPerformModeTest() { - SetMultischema(); Require.AllFeaturesSupported(ProviderFeatures.Multischema | ProviderFeatures.Multidatabase); - isMultischemaTest = true; + + SetMultischema(); + var catalog = GetCatalog(); CreateSchema(catalog, "Model1"); CreateSchema(catalog, "Model2"); @@ -635,24 +677,25 @@ public void MultischemaUpgrageInPerformModeTest() catalog = GetCatalog(); CreateColumn(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKey(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); - var addedColumnsNames = new[] {"Id", "FirstColumn", "MyEntity2Id"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.Int64)}; + CreateForeignKeyInDb(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + + var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; CreateTable(catalog, "Model2", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKey(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreatePrimaryKeyInDb(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); + CreateForeignKeyInDb(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); - ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); - ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); - ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); UpgradeDomain(DomainUpgradeMode.Perform, ignoreRules); ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); BuildDomainInValidateMode(ignoreRules); ValidateMyEntity(catalog, "Model2"); } @@ -660,9 +703,10 @@ public void MultischemaUpgrageInPerformModeTest() [Test] public void MultischemaUpgrageInPerformSafelyModeTest() { - SetMultischema(); Require.AllFeaturesSupported(ProviderFeatures.Multischema | ProviderFeatures.Multidatabase); - isMultischemaTest = true; + + SetMultischema(); + var catalog = GetCatalog(); CreateSchema(catalog, "Model1"); CreateSchema(catalog, "Model2"); @@ -670,24 +714,25 @@ public void MultischemaUpgrageInPerformSafelyModeTest() catalog = GetCatalog(); CreateColumn(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKey(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); - var addedColumnsNames = new[] {"Id", "FirstColumn", "MyEntity2Id"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.Int64)}; + CreateForeignKeyInDb(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + + var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; CreateTable(catalog, "Model2", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKey(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKey(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreatePrimaryKeyInDb(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); + CreateForeignKeyInDb(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); - ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); - ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); - ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); UpgradeDomain(DomainUpgradeMode.PerformSafely, ignoreRules); ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); BuildDomainInValidateMode(ignoreRules); ValidateMyEntity(catalog, "Model2"); } @@ -695,31 +740,33 @@ public void MultischemaUpgrageInPerformSafelyModeTest() [Test] public void MultidatabaseUpgradeInPerformModeTest() { - SetMultidatabase(); Require.AllFeaturesSupported(ProviderFeatures.Multidatabase); - isMultidatabaseTest = true; + + SetMultidatabase(); + BuildDomainAndFillData(); var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); CreateColumn(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); - CreateForeignKey(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); - var addedColumnsNames = new[] {"Id", "FirstColumn", "MyEntity2Id"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar), new SqlValueType(SqlType.Int64)}; + CreateForeignKeyInDb(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); + + var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; CreateTable(secondCatalog, "dbo", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); - CreatePrimaryKey(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); - CreateForeignKey(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); + CreatePrimaryKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); + CreateForeignKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("IgnoredTable").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); - ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); - ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); UpgradeDomain(DomainUpgradeMode.Perform, ignoreRules); ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); BuildDomainInValidateMode(ignoreRules); ValidateMyEntity(secondCatalog, "dbo", true); } @@ -734,24 +781,24 @@ public void MultidatabaseUpgradeInPerformSafelyModeTest() var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); CreateColumn(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); - CreateForeignKey(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); - var addedColumnsNames = new[] {"Id", "FirstColumn", "MyEntity2Id"}; - var addedColumnsTypes = new[] {new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.VarChar, 25), new SqlValueType(SqlType.Int64)}; + CreateForeignKeyInDb(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); + var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; + var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; CreateTable(secondCatalog, "dbo", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); - CreatePrimaryKey(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); - CreateForeignKey(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); + CreatePrimaryKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); + CreateForeignKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); var ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("IgnoredTable").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); - ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); - ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); UpgradeDomain(DomainUpgradeMode.PerformSafely, ignoreRules); ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); - ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); BuildDomainInValidateMode(ignoreRules); ValidateMyEntity(secondCatalog, "dbo", true); } @@ -761,10 +808,14 @@ private Domain BuildSimpleDomain(DomainUpgradeMode mode, IgnoreRuleCollection ig var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = mode; configuration.Types.Register(sourceType.Assembly, sourceType.Namespace); - if (additionalSourceTypes!=null) + + if (additionalSourceTypes != null) { additionalSourceTypes.ForEach((t) => configuration.Types.Register(t.Assembly, t.Namespace)); - if (ignoreRules!=null) + } + if (ignoreRules != null) { configuration.IgnoreRules = ignoreRules; + } + return Domain.Build(configuration); } @@ -773,39 +824,46 @@ private Domain BuildComplexDomain(DomainUpgradeMode mode, IgnoreRuleCollection i var config = DomainConfigurationFactory.Create(); config.UpgradeMode = mode; if (isMultischemaTest) { - foreach (var type in firstPartTypes) + foreach (var type in firstPartTypes) { config.MappingRules.Map(type.Assembly, type.Namespace).ToSchema("Model1"); + } - foreach (var type in secondPartTypes) + foreach (var type in secondPartTypes) { config.MappingRules.Map(type.Assembly, type.Namespace).ToSchema("Model2"); + } } else if (isMultidatabaseTest) { - foreach (var type in firstPartTypes) + foreach (var type in firstPartTypes) { config.MappingRules.Map(type.Assembly, type.Namespace).ToDatabase(Multimapping.MultidatabaseTest.Database1Name); + } - foreach (var type in secondPartTypes) + foreach (var type in secondPartTypes) { config.MappingRules.Map(type.Assembly, type.Namespace).ToDatabase(Multimapping.MultidatabaseTest.Database2Name); + } } config.DefaultSchema = "dbo"; config.DefaultDatabase = GetConnectionInfo().ConnectionUrl.GetDatabase(); - foreach (var type in firstPartTypes.Union(secondPartTypes)) + foreach (var type in firstPartTypes.Union(secondPartTypes)) { config.Types.Register(type.Assembly, type.Namespace); + } - if (ignoreRules!=null) + if (ignoreRules != null) { config.IgnoreRules = ignoreRules; + } + return Domain.Build(config); } private void BuildDomainAndFillData() { - Domain domain; - if (isMultidatabaseTest || isMultischemaTest) - domain = BuildComplexDomain(DomainUpgradeMode.Recreate, null, - new[] {typeof(Model1.Customer), typeof(ignorablePart.IgnoredTable)}, new[] {typeof(Model3.MyEntity1)}); - else - domain = BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof (Model1.Customer), typeof (ignorablePart.IgnoredTable)); + var domain = isMultidatabaseTest || isMultischemaTest + ? BuildComplexDomain(DomainUpgradeMode.Recreate, null, + new[] { typeof(Model1.Customer), typeof(ignorablePart.IgnoredTable) }, new[] { typeof(Model3.MyEntity1) }) + : BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model1.Customer), typeof(ignorablePart.IgnoredTable)); + + using (domain) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var author = new Model1.Author { @@ -814,7 +872,7 @@ private void BuildDomainAndFillData() Birthday = new DateTime(1812, 6, 18) }; var book = new Model1.Book { ISBN = "9780140440409", Title = "Oblomov" }; - book.Authors.Add(author); + _ = book.Authors.Add(author); var customer = new Model1.Customer { FirstName = "Alexey", LastName = "Kulakov", @@ -824,26 +882,26 @@ private void BuildDomainAndFillData() order["SomeIgnoredField"] = "Secret information for FBI :)"; if (isMultidatabaseTest || isMultischemaTest) { - new Model3.MyEntity1 {FirstColumn = "first"}; - new Model3.MyEntity2 {FirstColumn = "first"}; + _ = new Model3.MyEntity1 { FirstColumn = "first" }; + _ = new Model3.MyEntity2 { FirstColumn = "first" }; } transaction.Complete(); } - domain.Dispose(); } private void UpgradeDomain(DomainUpgradeMode mode) { IgnoreRuleCollection ignoreRules = new IgnoreRuleCollection(); - ignoreRules.IgnoreTable("IgnoredTable"); - ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order"); - ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author"); - using (var domain = BuildSimpleDomain(mode, ignoreRules, typeof (Model1.Customer))) + _ = ignoreRules.IgnoreTable("IgnoredTable"); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order"); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author"); + + using (var domain = BuildSimpleDomain(mode, ignoreRules, typeof(Model1.Customer))) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var currentCustomer = session.Query.All().First(c => c.LastName=="Kulakov"); - var order = session.Query.All().First(o => o.Customer.LastName==currentCustomer.LastName); - var newCustomer = new Model1.Customer {FirstName = "Fred", LastName = "Smith", Birthday = new DateTime(1998, 7, 9)}; + var currentCustomer = session.Query.All().First(c => c.LastName == "Kulakov"); + var order = session.Query.All().First(o => o.Customer.LastName == currentCustomer.LastName); + var newCustomer = new Model1.Customer { FirstName = "Fred", LastName = "Smith", Birthday = new DateTime(1998, 7, 9) }; order.Customer = newCustomer; changedOrderKey = order.Key; transaction.Complete(); @@ -852,15 +910,15 @@ private void UpgradeDomain(DomainUpgradeMode mode) private void UpgradeDomain(DomainUpgradeMode mode, IgnoreRuleCollection ignoreRules) { - using (var performDomain = BuildComplexDomain(mode, ignoreRules, new[] { typeof (Model1.Customer) }, new[] { typeof (Model3.MyEntity1) })) + using (var performDomain = BuildComplexDomain(mode, ignoreRules, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) })) using (var session = performDomain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var currentCustomer = session.Query.All().First(c => c.LastName=="Kulakov"); - var order = session.Query.All().First(o => o.Customer.LastName==currentCustomer.LastName); + var currentCustomer = session.Query.All().First(c => c.LastName == "Kulakov"); + var order = session.Query.All().First(o => o.Customer.LastName == currentCustomer.LastName); var newCustomer = new Model1.Customer { FirstName = "Fred", LastName = "Smith", Birthday = new DateTime(1998, 7, 9) }; order.Customer = newCustomer; changedOrderKey = order.Key; - var currentEntity = session.Query.All().First(ent => ent.FirstColumn=="first"); + var currentEntity = session.Query.All().First(ent => ent.FirstColumn == "first"); currentEntity.FirstColumn = "second"; transaction.Complete(); } @@ -870,12 +928,12 @@ private void BuildDomainInValidateMode() { var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Validate; - configuration.Types.Register(typeof (Model1.Customer).Assembly, typeof (Model1.Customer).Namespace); - configuration.Types.Register(typeof (ignorablePart.IgnoredTable).Assembly, typeof (ignorablePart.IgnoredTable).Namespace); + configuration.Types.Register(typeof(Model1.Customer).Assembly, typeof(Model1.Customer).Namespace); + configuration.Types.Register(typeof(ignorablePart.IgnoredTable).Assembly, typeof(ignorablePart.IgnoredTable).Namespace); using (var domain = Domain.Build(configuration)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var result = session.Query.All().First(o => o.Key==changedOrderKey); + var result = session.Query.All().First(o => o.Key == changedOrderKey); Assert.That(result["SomeIgnoredField"], Is.EqualTo("Secret information for FBI :)")); } } @@ -883,12 +941,12 @@ private void BuildDomainInValidateMode() private void BuildDomainInValidateMode(IgnoreRuleCollection ignoreRules) { var validateDomain = BuildComplexDomain(DomainUpgradeMode.Validate, ignoreRules, - new[] {typeof(Model1.Customer), typeof(ignorablePart.IgnoredTable)}, new[] {typeof(Model3.MyEntity1)}); + new[] { typeof(Model1.Customer), typeof(ignorablePart.IgnoredTable) }, new[] { typeof(Model3.MyEntity1) }); using (validateDomain) using (var session = validateDomain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var result = session.Query.All().First(o => o.Key==changedOrderKey); + var result = session.Query.All().First(o => o.Key == changedOrderKey); Assert.That(result["SomeIgnoredField"], Is.EqualTo("Secret information for FBI :)")); } } @@ -899,11 +957,13 @@ private Catalog GetCatalog(string catalogName = null) using (var sqlConnection = sqlDriver.CreateConnection()) { sqlConnection.Open(); sqlConnection.BeginTransaction(); - if (catalogName==null) + if (catalogName == null) { catalog = sqlDriver.ExtractCatalog(sqlConnection); + } else { - var sqlExtractionTaskList = new List(); - sqlExtractionTaskList.Add(new SqlExtractionTask(catalogName)); + var sqlExtractionTaskList = new List { + new SqlExtractionTask(catalogName) + }; catalog = sqlDriver.Extract(sqlConnection, sqlExtractionTaskList).Catalogs.First(); } sqlConnection.Commit(); @@ -912,18 +972,15 @@ private Catalog GetCatalog(string catalogName = null) return catalog; } - private ConnectionInfo GetConnectionInfo() - { - return DomainConfigurationFactory.Create().ConnectionInfo; - } + private ConnectionInfo GetConnectionInfo() => DomainConfigurationFactory.Create().ConnectionInfo; private void ExecuteNonQuery(string commandText) { using (var connection = sqlDriver.CreateConnection()) { connection.Open(); - var command = connection.CreateCommand(commandText); - command.ExecuteNonQuery(); - command.Dispose(); + using (var command = connection.CreateCommand(commandText)) { + _ = command.ExecuteNonQuery(); + } connection.Close(); } } @@ -933,12 +990,12 @@ private object ExecuteQuery(string commandText, int returnedColumnIndex) var result = new object(); using (var connection = sqlDriver.CreateConnection()) { connection.Open(); - var command = connection.CreateCommand(commandText); - var reader = command.ExecuteReader(); - if (reader.Read()) - result = reader.GetValue(returnedColumnIndex); - reader.Dispose(); - command.Dispose(); + using (var command = connection.CreateCommand(commandText)) + using (var reader = command.ExecuteReader()) { + if (reader.Read()) { + result = reader.GetValue(returnedColumnIndex); + } + } connection.Close(); } return result; @@ -946,89 +1003,112 @@ private object ExecuteQuery(string commandText, int returnedColumnIndex) private void ValidateMyEntity(Catalog catalog, string schema, bool useDatabasePrefix = false) { - var schemaForValidete = catalog.Schemas[schema]; - if (schemaForValidete==null) - schemaForValidete = catalog.Schemas[0]; - SqlTableRef myEntity2 = SqlDml.TableRef(schemaForValidete.Tables["MyEntity2"]); - SqlSelect select = SqlDml.Select(myEntity2); - var compileConfiguration = new SqlCompilerConfiguration(); - compileConfiguration.DatabaseQualifiedObjects = useDatabasePrefix; - var commandText = sqlDriver.Compile(select, compileConfiguration).GetCommandText(); + var schemaToValidete = catalog.Schemas[schema] ?? catalog.Schemas[0]; + + var myEntity2 = SqlDml.TableRef(schemaToValidete.Tables["MyEntity2"]); + var select = SqlDml.Select(myEntity2); + var commandText = sqlDriver.Compile(select, BuildCompilerConfig(useDatabasePrefix)).GetCommandText(); Assert.That(ExecuteQuery(commandText, 2), Is.EqualTo(DBNull.Value)); } - private void CreateForeignKey(Catalog catalog, string schema, string table, string column, string referencedTable, + private void CreateForeignKeyInDb(Catalog catalog, string schema, string table, string column, string referencedTable, string referencedColumn, string foreignKeyName, bool useDatabasePrefix = false) { - var schemaForAlter = catalog.Schemas[schema]; - if (schemaForAlter==null) - schemaForAlter = catalog.Schemas[0]; - var foreignKey = schemaForAlter.Tables[table].CreateForeignKey(foreignKeyName); - foreignKey.Columns.Add(schemaForAlter.Tables[table].TableColumns[column]); - foreignKey.ReferencedTable = schemaForAlter.Tables[referencedTable]; - foreignKey.ReferencedColumns.Add(schemaForAlter.Tables[referencedTable].TableColumns[referencedColumn]); - var alter = SqlDdl.Alter(schemaForAlter.Tables[table], SqlDdl.AddConstraint(foreignKey)); - var sqlComplieConfig = new SqlCompilerConfiguration(); - sqlComplieConfig.DatabaseQualifiedObjects = useDatabasePrefix; - string commandText = sqlDriver.Compile(alter, sqlComplieConfig).GetCommandText(); + var schemaToAlter = catalog.Schemas[schema] ?? catalog.Schemas[0]; + + var foreignKey = schemaToAlter.Tables[table].CreateForeignKey(foreignKeyName); + foreignKey.Columns.Add(schemaToAlter.Tables[table].TableColumns[column]); + foreignKey.ReferencedTable = schemaToAlter.Tables[referencedTable]; + foreignKey.ReferencedColumns.Add(schemaToAlter.Tables[referencedTable].TableColumns[referencedColumn]); + var alter = SqlDdl.Alter(schemaToAlter.Tables[table], SqlDdl.AddConstraint(foreignKey)); + var commandText = sqlDriver.Compile(alter, BuildCompilerConfig(useDatabasePrefix)).GetCommandText(); ExecuteNonQuery(commandText); } - private void CreatePrimaryKey(Catalog catalog, string schema, string table, string column, string primaryKeyName, bool useDatabasePrefix = false) + private void CreateForeignKeyLocally(Catalog catalog, string schema, string table, string column, string referencedTable, + string referencedColumn, string foreignKeyName, bool useDatabasePrefix = false) + { + var schemaToAlter = catalog.Schemas[schema] ?? catalog.Schemas[0]; + var foreignKey = schemaToAlter.Tables[table].CreateForeignKey(foreignKeyName); + foreignKey.Columns.Add(schemaToAlter.Tables[table].TableColumns[column]); + foreignKey.ReferencedTable = schemaToAlter.Tables[referencedTable]; + foreignKey.ReferencedColumns.Add(schemaToAlter.Tables[referencedTable].TableColumns[referencedColumn]); + } + + private void CreatePrimaryKeyInDb(Catalog catalog, string schema, string table, string column, string primaryKeyName, bool useDatabasePrefix = false) { - var schemaForAlter = catalog.Schemas[schema]; - if (schemaForAlter==null) - schemaForAlter = catalog.Schemas[0]; - var primaryKey = schemaForAlter.Tables[table].CreatePrimaryKey(primaryKeyName, - schemaForAlter.Tables[table].TableColumns[column]); - var alter = SqlDdl.Alter(schemaForAlter.Tables[table], SqlDdl.AddConstraint(primaryKey)); - var sqlComplieConfig = new SqlCompilerConfiguration(); - sqlComplieConfig.DatabaseQualifiedObjects = useDatabasePrefix; - string commandText = sqlDriver.Compile(alter, sqlComplieConfig).GetCommandText(); + var schemaToAlter = catalog.Schemas[schema] ?? catalog.Schemas[0]; + + var primaryKey = schemaToAlter.Tables[table].CreatePrimaryKey(primaryKeyName, + schemaToAlter.Tables[table].TableColumns[column]); + var alter = SqlDdl.Alter(schemaToAlter.Tables[table], SqlDdl.AddConstraint(primaryKey)); + var commandText = sqlDriver.Compile(alter, BuildCompilerConfig(useDatabasePrefix)).GetCommandText(); ExecuteNonQuery(commandText); } + private void CreatePrimaryKeyLocally(Catalog catalog, string schema, string table, string column, string primaryKeyName) + { + var schemaToAlter = catalog.Schemas[schema] ?? catalog.Schemas[0]; + _ = schemaToAlter.Tables[table].CreatePrimaryKey(primaryKeyName, + schemaToAlter.Tables[table].TableColumns[column]); + } + private void CreateColumn(Catalog catalog, string schema, string table, string columnName, SqlValueType columnType, bool useDatabasePrefix = false) { - var schemaForAlter = catalog.Schemas[schema]; - if (schemaForAlter==null) - schemaForAlter = catalog.Schemas[0]; - var column = schemaForAlter.Tables[table].CreateColumn(columnName, columnType); + var schemaToAlter = catalog.Schemas[schema] ?? catalog.Schemas[0]; + var column = schemaToAlter.Tables[table].CreateColumn(columnName, columnType); column.IsNullable = true; - SqlAlterTable alter = SqlDdl.Alter(schemaForAlter.Tables[table], SqlDdl.AddColumn(column)); - var sqlComplieConfig = new SqlCompilerConfiguration(); - sqlComplieConfig.DatabaseQualifiedObjects = useDatabasePrefix; - string commandText = sqlDriver.Compile(alter, sqlComplieConfig).GetCommandText(); + var alter = SqlDdl.Alter(schemaToAlter.Tables[table], SqlDdl.AddColumn(column)); + var commandText = sqlDriver.Compile(alter, BuildCompilerConfig(useDatabasePrefix)).GetCommandText(); ExecuteNonQuery(commandText); } private void CreateTable(Catalog catalog, string schema, string tableName, string[] columns, SqlValueType[] columnTypes, bool useDatabasePrefix = false) { - var schemaForAlter = catalog.Schemas[schema]; - if (schemaForAlter==null) - schemaForAlter = catalog.Schemas[0]; - var table = schemaForAlter.CreateTable(tableName); - - for (var i = 0; i < columns.Length; i++) - new TableColumn(table, columns[i], columnTypes[i]); - - SqlCreateTable create = SqlDdl.Create(table); - var sqlComplieConfig = new SqlCompilerConfiguration(); - sqlComplieConfig.DatabaseQualifiedObjects = useDatabasePrefix; - string commandText = sqlDriver.Compile(create, sqlComplieConfig).GetCommandText(); + var schemaToAlter = catalog.Schemas[schema] ?? catalog.Schemas[0]; + var table = schemaToAlter.CreateTable(tableName); + + for (var i = 0; i < columns.Length; i++) { + _ = new TableColumn(table, columns[i], columnTypes[i]); + } + + var create = SqlDdl.Create(table); + var commandText = sqlDriver.Compile(create, BuildCompilerConfig(useDatabasePrefix)).GetCommandText(); ExecuteNonQuery(commandText); } + private System.Action CreateTableDelayed(Catalog catalog, string schema, string tableName, string[] columns, SqlValueType[] columnTypes, bool useDatabasePrefix = false) + { + var schemaToAlter = catalog.Schemas[schema] ?? catalog.Schemas[0]; + var table = schemaToAlter.CreateTable(tableName); + + for (var i = 0; i < columns.Length; i++) { + _ = new TableColumn(table, columns[i], columnTypes[i]); + } + + var create = SqlDdl.Create(table); + var commandText = sqlDriver.Compile(create, BuildCompilerConfig(useDatabasePrefix)).GetCommandText(); + + return () => ExecuteNonQuery(commandText); + } + private void CreateSchema(Catalog catalog, string schemaName) { - if (catalog.Schemas[schemaName]==null) { - catalog.CreateSchema(schemaName); - SqlCreateSchema schemaCreate = SqlDdl.Create(catalog.Schemas[schemaName]); - string commandText = sqlDriver.Compile(schemaCreate).GetCommandText(); + if (catalog.Schemas[schemaName] == null) { + var schema = catalog.CreateSchema(schemaName); + var schemaCreate = SqlDdl.Create(schema); + var commandText = sqlDriver.Compile(schemaCreate).GetCommandText(); ExecuteNonQuery(commandText); } } + private static SqlCompilerConfiguration BuildCompilerConfig(bool useDatabasePrefix) + { + return new SqlCompilerConfiguration { + DatabaseQualifiedObjects = useDatabasePrefix + }; + } + private void SetMultidatabase() { isMultidatabaseTest = true; From fd801372f0b1b7ab15b84507d18c1b9329c1bdb6 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 18 Mar 2021 13:33:18 +0500 Subject: [PATCH 17/71] Make test work with all RDBMSs --- .../Storage/FieldSqlDefaultTest.cs | 72 ++++++++++++------- 1 file changed, 46 insertions(+), 26 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs b/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs index 41cd688b15..a05604b1ad 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2014 Xtensive LLC. +// Copyright (C) 2014-2021 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexey Kulakov @@ -7,6 +7,8 @@ using System; using System.Linq; using NUnit.Framework; +using Xtensive.Orm.Building; +using Xtensive.Orm.Building.Definitions; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Storage.FieldSqlDefaultTestModel; @@ -58,13 +60,32 @@ public class TestEntity : Entity [Field(DefaultValue = 12.12, DefaultSqlExpression = "12.12")] public decimal FDecimal { get; set; } - [Field(DefaultValue = "2012.12.12", DefaultSqlExpression = "'2013.12.13'")] + [Field(DefaultValue = "2012-12-12", DefaultSqlExpression = "'2013-12-13'")]// for oracle it will be set in IModule public DateTime FDateTime { get; set; } [Field(Length = 1000, DefaultValue = "default value", DefaultSqlExpression = "'sql value'")] public string FString { get; set; } } - + + public class OracleDefaultValueModifier : IModule + { + public void OnBuilt(Domain domain) + { + } + + public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) + { + if (StorageProviderInfo.Instance.Provider != StorageProvider.Oracle) { + return; + } + + var field = model.Types[nameof(TestEntity)].Fields[nameof(TestEntity.FDateTime)]; + field.DefaultValue = FormatDate(new DateTime(2012, 12, 12)); + field.DefaultSqlExpression = $"'{FormatDate(new DateTime(2013, 12, 13))}'"; + } + + private static string FormatDate(DateTime dateToFormat) => dateToFormat.ToString("dd-MMM-yyyy"); + } } namespace Xtensive.Orm.Tests.Storage @@ -78,6 +99,7 @@ public void MainTest() var configuration = base.BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(OracleDefaultValueModifier)); Domain = Domain.Build(configuration); var driver = TestSqlDriver.Create(Domain.Configuration.ConnectionInfo); @@ -85,31 +107,29 @@ public void MainTest() connection.Open(); var command = connection.CreateCommand(); var translator = driver.Translator; - command.CommandText = string.Format("INSERT INTO {0}({1}) values(1);", translator.QuoteIdentifier("TestEntity"), translator.QuoteIdentifier("Id")); - command.ExecuteNonQuery(); + command.CommandText = string.Format("INSERT INTO {0}({1}) values(1)", translator.QuoteIdentifier("TestEntity"), translator.QuoteIdentifier("Id")); + _ = command.ExecuteNonQuery(); connection.Close(); } - - using (var session = Domain.OpenSession()) { - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - Assert.AreEqual(1, entity.Id); - Assert.AreEqual(64, entity.FByte); - Assert.AreEqual(65, entity.FSByte); - Assert.AreEqual(66, entity.FShort); - Assert.AreEqual(67, entity.FUShort); - Assert.AreEqual(68, entity.FInt); - Assert.AreEqual(69, entity.FUInt); - Assert.AreEqual(70L, entity.FLong); - Assert.AreEqual(71L, entity.FULong); - Assert.AreEqual(72.0, entity.FFloat); - Assert.AreEqual(73.0, entity.FDouble); - Assert.AreEqual(12.12M, entity.FDecimal); - Assert.AreEqual(DateTime.Parse("2013.12.13"), entity.FDateTime); - Assert.AreEqual("sql value", entity.FString); - transaction.Complete(); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + Assert.AreEqual(1, entity.Id); + Assert.AreEqual(64, entity.FByte); + Assert.AreEqual(65, entity.FSByte); + Assert.AreEqual(66, entity.FShort); + Assert.AreEqual(67, entity.FUShort); + Assert.AreEqual(68, entity.FInt); + Assert.AreEqual(69, entity.FUInt); + Assert.AreEqual(70L, entity.FLong); + Assert.AreEqual(71L, entity.FULong); + Assert.AreEqual(72.0, entity.FFloat); + Assert.AreEqual(73.0, entity.FDouble); + Assert.AreEqual(12.12M, entity.FDecimal); + Assert.AreEqual(DateTime.Parse("2013.12.13"), entity.FDateTime); + Assert.AreEqual("sql value", entity.FString); + transaction.Complete(); } } @@ -128,7 +148,7 @@ public void DefaultValueTestForKeyFieldTest() var command = connection.CreateCommand(); var translator = driver.Translator; command.CommandText = string.Format("INSERT INTO {0} DEFAULT VALUES;", translator.QuoteIdentifier("TestEntity1")); - command.ExecuteNonQuery(); + _ = command.ExecuteNonQuery(); connection.Close(); } From 86a072b3893858b4059745eca4cecf9637b4c122 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 18 Mar 2021 13:48:30 +0500 Subject: [PATCH 18/71] Much informative exception for unsupported types Plus code style improvements --- .../Sql/Compiler/SqlTranslator.cs | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/Orm/Xtensive.Orm/Sql/Compiler/SqlTranslator.cs b/Orm/Xtensive.Orm/Sql/Compiler/SqlTranslator.cs index 8635e3428c..ad2ae005e6 100644 --- a/Orm/Xtensive.Orm/Sql/Compiler/SqlTranslator.cs +++ b/Orm/Xtensive.Orm/Sql/Compiler/SqlTranslator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2003-2021 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.Globalization; @@ -1577,21 +1577,28 @@ public virtual string Translate(ReferentialAction action) public virtual string Translate(SqlValueType type) { - if (type.TypeName!=null) + if (type.TypeName != null) { return type.TypeName; + } + + var dataTypeInfo = Driver.ServerInfo.DataTypes[type.Type]; + if (dataTypeInfo == null) { + throw new NotSupportedException(string.Format(Strings.ExTypeXIsNotSupported, + (type.Type == SqlType.Unknown) ? type.TypeName : type.Type.Name)); + } + + var typeName = dataTypeInfo.NativeTypes.First(); - DataTypeInfo dti = Driver.ServerInfo.DataTypes[type.Type]; - if (dti==null) - throw new NotSupportedException(String.Format(Strings.ExTypeXIsNotSupported, type.Type)); - string text = dti.NativeTypes.First(); - - if (type.Length.HasValue) - return text + "(" + type.Length + ")"; - if (type.Precision.HasValue && type.Scale.HasValue) - return text + "(" + type.Precision + "," + type.Scale + ")"; - if (type.Precision.HasValue) - return text + "(" + type.Precision + ")"; - return text; + if (type.Length.HasValue) { + return $"{typeName}({type.Length})"; + } + if (type.Precision.HasValue && type.Scale.HasValue) { + return $"{typeName}({type.Precision},{type.Scale})"; + } + if (type.Precision.HasValue) { + return $"{typeName}({type.Precision})"; + } + return typeName; } public virtual string Translate(SqlFunctionType type) From 5cd76c25f94f05e7a173fcf0570c53b93158cc72 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 18 Mar 2021 13:57:31 +0500 Subject: [PATCH 19/71] Remove useless white spaces or tabs --- Orm/Xtensive.Orm.Tests.Framework/Orm.config | 2 +- Orm/Xtensive.Orm.Tests/Chinook.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests.Framework/Orm.config b/Orm/Xtensive.Orm.Tests.Framework/Orm.config index f4827135a7..e1b47225c1 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Orm.config +++ b/Orm/Xtensive.Orm.Tests.Framework/Orm.config @@ -118,7 +118,7 @@ - + diff --git a/Orm/Xtensive.Orm.Tests/Chinook.xml b/Orm/Xtensive.Orm.Tests/Chinook.xml index 7fddf2b37c..c51f7afd7b 100644 --- a/Orm/Xtensive.Orm.Tests/Chinook.xml +++ b/Orm/Xtensive.Orm.Tests/Chinook.xml @@ -1,4 +1,4 @@ - + @@ -61140,7 +61140,7 @@ 3 241828000000000 110 Raeburn Pl - Edinburgh + Edinburgh United Kingdom EH4 1HH From 8df99b7b28ae75711d48cbf011281f05903a9aef Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 18 Mar 2021 21:20:38 +0500 Subject: [PATCH 20/71] Make test to be applicable to all storages Types that work in all RDBMSs are in X entity, those that specific to certain subset of RDBMSs are moved to separate Y and Z entities --- .../Storage/FieldDefaultValueTest.cs | 114 ++++++++++++++---- 1 file changed, 89 insertions(+), 25 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs b/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs index 6a9d6e3137..233621bde6 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2008.09.19 @@ -149,18 +149,9 @@ public class X : Entity [Field(DefaultValue = 1000)] public TimeSpan FTimeSpan { get; set; } - [Field(Length = 1000, DefaultValue = new byte[] {10,10,10,10})] - public byte[] FByteArray { get; set; } - - [Field(Length = int.MaxValue, DefaultValue = new byte[] {10,10,10,10})] - public byte[] FLongByteArray { get; set; } - [Field(Length = 1000, DefaultValue = "default value")] public string FString { get; set; } - [Field(Length = int.MaxValue, DefaultValue = "default value")] - public string FLongString { get; set; } - [Field(DefaultValue = EByte.Max)] public EByte FEByte { get; set; } @@ -265,6 +256,31 @@ public class X : Entity [Field(DefaultValue = CodeRegistry.EnumKeyValue)] public EnumKeyEntity EnumKeyEntityRef { get; set; } } + + [HierarchyRoot] + [Serializable] + public class Y : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field(Length = int.MaxValue, DefaultValue = "default value")] + public string FLongString { get; set; } + } + + [HierarchyRoot] + [Serializable] + public class Z : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field(Length = 1000, DefaultValue = new byte[] { 10, 10, 10, 10 })] + public byte[] FByteArray { get; set; } + + [Field(Length = int.MaxValue, DefaultValue = new byte[] { 10, 10, 10, 10 })] + public byte[] FLongByteArray { get; set; } + } } namespace Xtensive.Orm.Tests.Storage @@ -275,28 +291,45 @@ public class FieldDefaultValueTest : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.Register(typeof (X).Assembly, typeof (X).Namespace); + config.Types.Register(typeof(XRef)); + config.Types.Register(typeof(EnumKeyEntity)); + config.Types.Register(typeof(X)); + if (SupportsDefaultForLongString()) { + config.Types.Register(typeof(Y)); + } + if (SupportsDefaultForArrays()) { + config.Types.Register(typeof(Z)); + } return config; } [Test] public void DefaultValuesTest() { - using (Domain.OpenSession()) { - Key key; - using (var t = Session.Current.OpenTransaction()) { + using (var session = Domain.OpenSession()) { + Key keyX; + Key keyY = null; + Key keyZ = null; + using (var t = session.OpenTransaction()) { // To be sure that the reference field (X.Ref) would have meaning - new XRef(new Guid(CodeRegistry.GuidKeyValue)); - new EnumKeyEntity(CodeRegistry.EnumKeyValue); - key = new X().Key; + _ = new XRef(new Guid(CodeRegistry.GuidKeyValue)); + _ = new EnumKeyEntity(CodeRegistry.EnumKeyValue); + keyX = new X().Key; + + if (SupportsDefaultForLongString()) { + keyY = new Y().Key; + } + + if(SupportsDefaultForArrays()) { + keyZ = new Z().Key; + } t.Complete(); } - using (var t = Session.Current.OpenTransaction()) { - X x = Query.SingleOrDefault(key); + using (var t = session.OpenTransaction()) { + var x = session.Query.SingleOrDefault(keyX); Assert.AreEqual(true, x.FBool); Assert.AreEqual(byte.MaxValue, x.FByte); - Assert.AreEqual(new byte[] {10, 10, 10, 10}, x.FByteArray); Assert.AreEqual(DateTime.Parse("2012.12.12"), x.FDateTime); Assert.AreEqual(12.12M, x.FDecimal); Assert.AreEqual(float.MaxValue, x.FDouble); @@ -312,8 +345,7 @@ public void DefaultValuesTest() Assert.AreEqual(new Guid(CodeRegistry.GuidDefaultValue), x.FGuid); Assert.AreEqual(int.MaxValue, x.FInt); Assert.AreEqual(long.MaxValue, x.FLong); - Assert.AreEqual(new byte[] {10, 10, 10, 10}, x.FLongByteArray); - Assert.AreEqual("default value", x.FLongString); + Assert.AreEqual(sbyte.MaxValue, x.FSByte); Assert.AreEqual(short.MaxValue, x.FShort); Assert.AreEqual("default value", x.FString); @@ -348,6 +380,16 @@ public void DefaultValuesTest() Assert.IsNotNull(x.Ref); Assert.IsNotNull(x.EnumKeyEntityRef); + if (SupportsDefaultForLongString()) { + var y = session.Query.SingleOrDefault(keyY); + Assert.AreEqual("default value", y.FLongString); + } + if (SupportsDefaultForArrays()) { + var z = session.Query.SingleOrDefault(keyZ); + Assert.AreEqual(new byte[] { 10, 10, 10, 10 }, z.FByteArray); + Assert.AreEqual(new byte[] { 10, 10, 10, 10 }, z.FLongByteArray); + } + t.Complete(); } } @@ -358,9 +400,31 @@ public void ValidateTest() { var configuration = BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Validate; - configuration.Types.Register(typeof (X)); + configuration.Types.Register(typeof(X)); + if (SupportsDefaultForLongString()) { + configuration.Types.Register(typeof(Y)); + } + if (SupportsDefaultForArrays()) { + configuration.Types.Register(typeof(Z)); + } var domain = Domain.Build(configuration); domain.Dispose(); } + + private bool SupportsDefaultForArrays() + { + switch (StorageProviderInfo.Instance.Provider) { + case StorageProvider.Firebird: + case StorageProvider.MySql: + return false; + default: + return true; + } + } + + private bool SupportsDefaultForLongString() + { + return StorageProviderInfo.Instance.Provider != StorageProvider.MySql; + } } } \ No newline at end of file From c642f05102d0d6d2020f6762b4d118b6576801c3 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 18 Mar 2021 21:22:35 +0500 Subject: [PATCH 21/71] Fix format for float and double literal values --- .../Sql.Drivers.Firebird/v2_5/Translator.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Translator.cs b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Translator.cs index 795ae91dd2..e390ada330 100644 --- a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Translator.cs +++ b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Translator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Csaba Beer // Created: 2011.01.17 @@ -28,6 +28,10 @@ public override string TimeSpanFormatString get { return string.Empty; } } + public override string FloatFormatString => $"{base.FloatFormatString}e0"; + + public override string DoubleFormatString => $"{base.DoubleFormatString}e0"; + /// public override string QuoteIdentifier(params string[] names) { From e437d3704c7c3f0cc271712b46f20592deb7aec3 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 12:46:43 +0500 Subject: [PATCH 22/71] RoundingTest: SQLite no Power support handled --- .../Storage/Providers/Sql/RoundingTest.cs | 135 +++++++++++++----- 1 file changed, 98 insertions(+), 37 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs index 02246745ef..210516075a 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2009-2021 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -61,75 +61,132 @@ public void FloorTest() } [Test] - public void RoundDefaultTest() + public void RoundDefaultToZeroDigitsTest() { Query.All() .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal), x.Key))); - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1) }) - .GroupBy(x => x.DecimalRound) - .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1), x.Key))); - Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double), x.Key))); - - Query.All() - .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1) }) - .GroupBy(x => x.DoubleRound) - .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1), x.Key))); } [Test] - public void RoundToEvenTest() + public void RoundDefaultToNonZeroDigitsTest() + { + if (ExpectNotSupported()) { + var ex = Assert.Throws(() => + Query.All().Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1) }) + .GroupBy(x => x.DecimalRound).Run()); + Assert.That(ex.InnerException, Is.InstanceOf()); + Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); + + ex = Assert.Throws(() => + Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1) }) + .GroupBy(x => x.DoubleRound).Run()); + Assert.That(ex.InnerException, Is.InstanceOf()); + Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); + } + else { + Query.All() + .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1) }) + .GroupBy(x => x.DecimalRound) + .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1), x.Key))); + + Query.All() + .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1) }) + .GroupBy(x => x.DoubleRound) + .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1), x.Key))); + } + } + + [Test] + public void RoundToEvenToZeroDigitsTest() { Query.All() .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, MidpointRounding.ToEven) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, MidpointRounding.ToEven), x.Key))); - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.ToEven) }) - .GroupBy(x => x.DecimalRound) - .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1, MidpointRounding.ToEven), x.Key))); - Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, MidpointRounding.ToEven) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, MidpointRounding.ToEven), x.Key))); + } - Query.All() - .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.ToEven) }) - .GroupBy(x => x.DoubleRound) - .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1, MidpointRounding.ToEven), x.Key))); + [Test] + public void RoundToEvenToNonZeroDigitsTest() + { + if (ExpectNotSupported()) {// sqlite has no support for Power operation + var ex = Assert.Throws(() => + Query.All().Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.ToEven) }) + .GroupBy(x => x.DecimalRound).Run()); + Assert.That(ex.InnerException, Is.InstanceOf()); + Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); + + ex = Assert.Throws(() => + Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.ToEven) }) + .GroupBy(x => x.DoubleRound).Run()); + Assert.That(ex.InnerException, Is.InstanceOf()); + Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); + } + else { + Query.All() + .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.ToEven) }) + .GroupBy(x => x.DecimalRound) + .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1, MidpointRounding.ToEven), x.Key))); + + Query.All() + .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.ToEven) }) + .GroupBy(x => x.DoubleRound) + .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1, MidpointRounding.ToEven), x.Key))); + } } [Test] - public void RoundAwayFromZeroTest() + public void RoundAwayFromZeroToZeroDigitsTest() { Query.All() .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, MidpointRounding.AwayFromZero), x.Key))); - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.AwayFromZero) }) - .GroupBy(x => x.DecimalRound) - .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1, MidpointRounding.AwayFromZero), x.Key))); - Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, MidpointRounding.AwayFromZero), x.Key))); + } - Query.All() - .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.AwayFromZero) }) - .GroupBy(x => x.DoubleRound) - .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1, MidpointRounding.AwayFromZero), x.Key))); + [Test] + public void RoundAwayFromZeroToNonZeroDigitsTest() + { + if (ExpectNotSupported()) { + var ex = Assert.Throws(() => + Query.All().Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.AwayFromZero) }) + .GroupBy(x => x.DecimalRound).Run()); + Assert.That(ex.InnerException, Is.InstanceOf()); + Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); + + ex = Assert.Throws(() => + Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.AwayFromZero) }) + .GroupBy(x => x.DoubleRound).Run()); + Assert.That(ex.InnerException, Is.InstanceOf()); + Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); + } + else { + Query.All() + .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.AwayFromZero) }) + .GroupBy(x => x.DecimalRound) + .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1, MidpointRounding.AwayFromZero), x.Key))); + + Query.All() + .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.AwayFromZero) }) + .GroupBy(x => x.DoubleRound) + .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1, MidpointRounding.AwayFromZero), x.Key))); + } } public override void TestFixtureSetUp() @@ -171,8 +228,9 @@ public override void TestFixtureSetUp() -72244.3m, -72244.5m, -72244.6m }; - foreach (var value in testValues) - new X { FDouble = (double)value, FDecimal = value }; + foreach (var value in testValues) { + _ = new X { FDouble = (double) value, FDecimal = value }; + } } public override void TestFixtureTearDown() @@ -190,13 +248,16 @@ protected override DomainConfiguration BuildConfiguration() private static void AreEqual(decimal expected, decimal actual) { - if (Math.Abs(expected - actual) > DecimalDelta) + if (Math.Abs(expected - actual) > DecimalDelta) { Assert.Fail("expected {0} actual {1}", expected, actual); + } } - private void AreEqual(double expected, double actual) + private void AreEqual(double expected, double actual) => Assert.AreEqual(expected, actual, DoubleDelta); + + private bool ExpectNotSupported() { - Assert.AreEqual(expected, actual, DoubleDelta); + return StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Sqlite); } } } \ No newline at end of file From e17575488ac897f3f2ef701b7000794e7efb93e6 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 13:12:56 +0500 Subject: [PATCH 23/71] Make test to be up to made changes --- .../Storage/MemoryProviderTest.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs b/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs index 6fe78bda30..672c4a00d8 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 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 // Created: 2013.02.14 @@ -59,7 +59,7 @@ public void TestFixtureSetUp() public void MainTest() { var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (TheEntity).Assembly, typeof (TheEntity).Namespace); + configuration.Types.Register(typeof(TheEntity).Assembly, typeof(TheEntity).Namespace); configuration.ConnectionInfo = new ConnectionInfo(WellKnown.Provider.Sqlite, "Data Source=:memory:"); configuration.UpgradeMode = DomainUpgradeMode.Perform; @@ -70,7 +70,7 @@ public void MainTest() using (var session = domain.OpenSession()) using (var tx = session.OpenTransaction()) { - new TheEntity {Value = "in-memory"}; + _ = new TheEntity {Value = "in-memory"}; CheckSingleConnection(session, singleConnection); tx.Complete(); } @@ -94,7 +94,8 @@ public void MainTest() domain.Dispose(); - AssertEx.Throws(() => singleConnection.State.ToString()); + Assert.DoesNotThrow(() => singleConnection.State.ToString()); + Assert.That(singleConnection.State, Is.EqualTo(ConnectionState.Closed)); } [TearDown] From d654142634bb85e134dbd974a356b7719dfa9dfe Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 13:13:39 +0500 Subject: [PATCH 24/71] Copyright for file --- Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs index 210516075a..e3123a1d5d 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs @@ -1,6 +1,6 @@ // Copyright (C) 2009-2021 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Denis Krjuchkov // Created: 2009.06.09 From ce8109045505caaa68bdbd3e4c2906ce1e358719 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 15:50:12 +0500 Subject: [PATCH 25/71] Session: Remove check for incomple asyncronous operations as it done in master --- .../ConcurrentCommandProcessorExecution.cs | 322 ------------------ Orm/Xtensive.Orm/Orm/Session.Persist.cs | 7 - 2 files changed, 329 deletions(-) delete mode 100644 Orm/Xtensive.Orm.Tests/Storage/ConcurrentCommandProcessorExecution.cs diff --git a/Orm/Xtensive.Orm.Tests/Storage/ConcurrentCommandProcessorExecution.cs b/Orm/Xtensive.Orm.Tests/Storage/ConcurrentCommandProcessorExecution.cs deleted file mode 100644 index 4b2e35712c..0000000000 --- a/Orm/Xtensive.Orm.Tests/Storage/ConcurrentCommandProcessorExecution.cs +++ /dev/null @@ -1,322 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Orm.Configuration; -using Xtensive.Orm.Tests.Storage.ConcurrentCommandProcessorExecutionModel; - -namespace Xtensive.Orm.Tests.Storage.ConcurrentCommandProcessorExecutionModel -{ - [HierarchyRoot] - public class TestEntity : Entity - { - [Field, Key] - public int Id { get; private set; } - - [Field] - public string Name { get; set; } - - [Field] - public DateTime CreationDate { get; set; } - - [Field] - public long Value { get; set; } - - public TestEntity(Session session) - : base(session) - { - } - } - - [HierarchyRoot] - public class EntitySetContainer : Entity - { - [Field, Key] - public int Id { get; private set; } - - [Field] - public EntitySet EntitySet { get; set; } - - public EntitySetContainer(Session session) - : base(session) - { - } - } -} - -namespace Xtensive.Orm.Tests.Storage -{ - public class ConcurrentCommandProcessorExecution : AutoBuildTest - { - private const int OneBatchSizedTaskCollectionCount = SessionConfiguration.DefaultBatchSize; - private const int TwoBatchSizedTaskCollectionCount = SessionConfiguration.DefaultBatchSize * 2; - private const int MoreThatTwoBatchSizedTaskCollectionCount = SessionConfiguration.DefaultBatchSize * 2 + 2; - - protected override DomainConfiguration BuildConfiguration() - { - var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (TestEntity).Assembly, typeof (TestEntity).Namespace); - configuration.UpgradeMode = DomainUpgradeMode.Recreate; - return configuration; - } - - protected override void PopulateData() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityCount = 1000; - for (int i = 0; i < entityCount; i++) { - new TestEntity(session) { Name = "A", Value = i, CreationDate = DateTime.Now.AddSeconds(i) }; - if (i % 10==0) - session.SaveChanges(); - } - transaction.Complete(); - } - } - - [Test] - public async Task InseparableBatchTest() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> longListOfQueries = new List>(OneBatchSizedTaskCollectionCount); - int value = 1; - while (longListOfQueries.Count < OneBatchSizedTaskCollectionCount) { - var closureValue = value; - longListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value += 1; - } - - var task = longListOfQueries.First().AsAsync(); - var fastBatch = await session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - await task; - - int countBefore = 1; - foreach (var query in longListOfQueries) { - var actualCount = query.Count(); - var expectedCount = countBefore; - Console.WriteLine(actualCount); - Assert.That(actualCount, Is.EqualTo(expectedCount)); - countBefore = countBefore + 1; - } - } - } - - [Test] - public async Task SeparableBatchTest01() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> longListOfQueries = new List>(TwoBatchSizedTaskCollectionCount); - int value = 1; - while (longListOfQueries.Count < TwoBatchSizedTaskCollectionCount) { - var closureValue = value; - longListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value += 1; - } - - var task = longListOfQueries.First().AsAsync(); - var fastBatch = await session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - await task; - - int countBefore = 1; - foreach (var query in longListOfQueries) { - var actualCount = query.Count(); - var expectedCount = countBefore; - Console.WriteLine(actualCount); - Assert.That(actualCount, Is.EqualTo(expectedCount)); - countBefore = countBefore + 1; - } - } - } - - [Test] - public async Task SeparableBatchTest02() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> longListOfQueries = new List>(MoreThatTwoBatchSizedTaskCollectionCount); - int value = 1; - while (longListOfQueries.Count < MoreThatTwoBatchSizedTaskCollectionCount) { - var closureValue = value; - longListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value += 1; - } - - var task = longListOfQueries.First().AsAsync(); - var fastBatch = await session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - await task; - - int countBefore = 1; - foreach (var query in longListOfQueries) { - var actualCount = query.Count(); - var expectedCount = countBefore; - Console.WriteLine(actualCount); - Assert.That(actualCount, Is.EqualTo(expectedCount)); - countBefore = countBefore + 1; - } - } - } - - [Test] - public async Task ActualPersistAfterBatchFinishedTest01() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> looooongListOfQueries = new List>(OneBatchSizedTaskCollectionCount); - int value = 1; - while (looooongListOfQueries.Count < OneBatchSizedTaskCollectionCount) { - var closureValue = value; - looooongListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value++; - } - - var task = looooongListOfQueries.First().AsAsync(); - new TestEntity(session) {Value = 0}; - new TestEntity(session) {Value = 0}; - var result1 = await task; - var anotherTask = session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - var result2 = await anotherTask; - - int countBefore = 1; - foreach (var query in looooongListOfQueries) { - var actualCount = query.Count(); - var expectedCount = countBefore; - Console.WriteLine(actualCount); - Assert.That(actualCount, Is.EqualTo(expectedCount)); - countBefore = countBefore + 1; - } - } - } - - [Test] - public async Task ActualPersistAfterBatchFinishedTest02() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> looooongListOfQueries = new List>(MoreThatTwoBatchSizedTaskCollectionCount); - int value = 1; - while (looooongListOfQueries.Count < MoreThatTwoBatchSizedTaskCollectionCount) { - var closureValue = value; - looooongListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value++; - } - - var task = looooongListOfQueries.First().AsAsync(); - new TestEntity(session) {Value = 0}; - new TestEntity(session) {Value = 0}; - var result1 = await task; - var anotherTask = session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - - var result2 = await anotherTask; - - int countBefore = 1; - foreach (var query in looooongListOfQueries) { - var actualCount = query.Count(); - var expectedCount = countBefore; - Console.WriteLine(actualCount); - Assert.That(actualCount, Is.EqualTo(expectedCount)); - countBefore = countBefore + 1; - } - } - } - - [Test] - public async Task PersistDuringNonSeparableBatchExecutionTest01() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> longListOfQueries = new List>(OneBatchSizedTaskCollectionCount); - int value = 1; - while (longListOfQueries.Count < OneBatchSizedTaskCollectionCount){ - var closureValue = value; - longListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value += 1; - } - - var task = longListOfQueries.First().AsAsync(); - new TestEntity(session) {Value = 0}; - new TestEntity(session) {Value = 0}; - var anotherTask = session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - var result1 = await task; - Assert.ThrowsAsync(async () => await anotherTask); - } - } - - [Test] - public async Task PersistDuringNonSeparableBatchExecutionTest02() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> longListOfQueries = new List>(OneBatchSizedTaskCollectionCount); - int value = 1; - while (longListOfQueries.Count < OneBatchSizedTaskCollectionCount) { - var closureValue = value; - longListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value += 1; - } - - var task = longListOfQueries.First().AsAsync(); - new TestEntity(session) {Value = 0}; - new TestEntity(session) {Value = 0}; - var anotherTask = session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - try { - Assert.ThrowsAsync(async () => await anotherTask); - } - finally { - var result2 = await task; - } - } - } - - [Test] - public async Task PersistDuringSeparableBatchExecutionTest01() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> longListOfQueries = new List>(MoreThatTwoBatchSizedTaskCollectionCount); - int value = 1; - while (longListOfQueries.Count < MoreThatTwoBatchSizedTaskCollectionCount) { - var closureValue = value; - longListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value += 1; - } - - var task = longListOfQueries.First().AsAsync(); - new TestEntity(session) { Value = 0 }; - new TestEntity(session) { Value = 0 }; - var anotherTask = session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - var result1 = await task; - Assert.ThrowsAsync(async () => await anotherTask); - } - } - - [Test] - public async Task PersistDuringSeparableBatchExecutionTest02() - { - using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - List> longListOfQueries = new List>(MoreThatTwoBatchSizedTaskCollectionCount); - int value = 1; - while (longListOfQueries.Count < MoreThatTwoBatchSizedTaskCollectionCount) { - var closureValue = value; - longListOfQueries.Add(session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < closureValue))); - value += 1; - } - - var task = longListOfQueries.First().AsAsync(); - new TestEntity(session) {Value = 0}; - new TestEntity(session) {Value = 0}; - var anotherTask = session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value > 10)).AsAsync(); - try { - Assert.ThrowsAsync(async () => await anotherTask); - } - finally { - var result2 = await task; - } - } - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Session.Persist.cs b/Orm/Xtensive.Orm/Orm/Session.Persist.cs index c6d465130b..a3b0d9f116 100644 --- a/Orm/Xtensive.Orm/Orm/Session.Persist.cs +++ b/Orm/Xtensive.Orm/Orm/Session.Persist.cs @@ -73,7 +73,6 @@ internal void Persist(PersistReason reason) EnsureNotDisposed(); if (IsPersisting || EntityChangeRegistry.Count==0) return; - EnsureAllAsyncQueriesFinished(); var performPinning = pinner.RootCount > 0; if (performPinning || (disableAutoSaveChanges && !Configuration.Supports(SessionOptions.NonTransactionalEntityStates))) @@ -278,11 +277,5 @@ private void ProcessChangesOfEntitySets(Action action) foreach (var entitySet in itemsToProcess) action.Invoke(entitySet); } - - private void EnsureAllAsyncQueriesFinished() - { - if (CommandProcessorContextProvider.AliveContextCount > 0) - throw new InvalidOperationException(Strings.ExUnableToSaveModifiedEntitesBecauseSomeAsynchronousQueryIsIncomplete); - } } } \ No newline at end of file From c434a385aa37e49651f3a18abab6ce12ea34427e Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 16:17:07 +0500 Subject: [PATCH 26/71] Fix accidentally broken build --- .../AsyncQueries/AsAsyncTaskExtensionTest.cs | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncTaskExtensionTest.cs b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncTaskExtensionTest.cs index 7c0e7a4584..0ce0816087 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncTaskExtensionTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncTaskExtensionTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2019 Xtensive LLC. +// Copyright (C) 2019-2021 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexey Kulakov @@ -13,6 +13,45 @@ using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Storage.ConcurrentCommandProcessorExecutionModel; +namespace Xtensive.Orm.Tests.Storage.ConcurrentCommandProcessorExecutionModel +{ + [HierarchyRoot] + public class TestEntity : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field] + public string Name { get; set; } + + [Field] + public DateTime CreationDate { get; set; } + + [Field] + public long Value { get; set; } + + public TestEntity(Session session) + : base(session) + { + } + } + + [HierarchyRoot] + public class EntitySetContainer : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field] + public EntitySet EntitySet { get; set; } + + public EntitySetContainer(Session session) + : base(session) + { + } + } +} + namespace Xtensive.Orm.Tests.Storage { public class AsAsyncTaskExtensionTest : AutoBuildTest From 34af791a6f5134d3cffa941d4e9cb04a05fa393c Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 16:39:39 +0500 Subject: [PATCH 27/71] AsAsyncExtensionTest improvements also rename --- ...tensionTest.cs => AsAsyncExtensionTest.cs} | 59 +++++++++---------- 1 file changed, 27 insertions(+), 32 deletions(-) rename Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/{AsAsyncTaskExtensionTest.cs => AsAsyncExtensionTest.cs} (74%) diff --git a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncTaskExtensionTest.cs b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncExtensionTest.cs similarity index 74% rename from Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncTaskExtensionTest.cs rename to Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncExtensionTest.cs index 0ce0816087..d4b3af984b 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncTaskExtensionTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/AsAsyncExtensionTest.cs @@ -1,6 +1,6 @@ // Copyright (C) 2019-2021 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2019.09.12 @@ -54,7 +54,7 @@ public EntitySetContainer(Session session) namespace Xtensive.Orm.Tests.Storage { - public class AsAsyncTaskExtensionTest : AutoBuildTest + public class AsAsyncExtensionTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { @@ -70,7 +70,7 @@ protected override void PopulateData() using (var transaction = session.OpenTransaction()) { var container = new EntitySetContainer(session); foreach (var i in Enumerable.Range(-100, 200)) { - container.EntitySet.Add(new TestEntity(session) {Value = i}); + _ = container.EntitySet.Add(new TestEntity(session) {Value = i}); } transaction.Complete(); } @@ -82,7 +82,7 @@ public async Task PureEnumerableTest() var task = AsEnumerable(1, 2, 3, 4).AsAsync(); Assert.That(task.IsCompleted, Is.True); - int before = 1; + var before = 1; foreach (var value in await task) { Assert.That(value, Is.EqualTo(before)); before++; @@ -96,7 +96,7 @@ public async Task CollectionAsEnumerableTest() var task = list.AsAsync(); Assert.That(task.IsCompleted, Is.True); - int before = 1; + var before = 1; foreach (var value in await task) { Assert.That(value, Is.EqualTo(before)); before++; @@ -106,11 +106,11 @@ public async Task CollectionAsEnumerableTest() [Test] public async Task QueryableAsEnumearbleTest() { - IQueryable queryableEnumeable = new EnumerableQuery(Enumerable.Range(-100, 200).ToArray()).Where(v => v < 5 && v > 0); + var queryableEnumeable = new EnumerableQuery(Enumerable.Range(-100, 200).ToArray()).Where(v => v < 5 && v > 0); var task = queryableEnumeable.AsEnumerable().AsAsync(); Assert.That(task.IsCompleted, Is.True); - int before = 1; + var before = 1; foreach (var value in await task) { Assert.That(value, Is.EqualTo(before)); before++; @@ -120,11 +120,11 @@ public async Task QueryableAsEnumearbleTest() [Test] public async Task QueryableTest() { - IQueryable queryableEnumeable = new EnumerableQuery(Enumerable.Range(-100, 200).ToArray()).Where(v => v < 5 && v > 0); + var queryableEnumeable = new EnumerableQuery(Enumerable.Range(-100, 200).ToArray()).Where(v => v < 5 && v > 0); var task = queryableEnumeable.AsAsync(); Assert.That(task.IsCompleted, Is.True); - int before = 1; + var before = 1; foreach (var value in await task) { Assert.That(value, Is.EqualTo(before)); before++; @@ -136,11 +136,10 @@ public async Task DoQueryableAsEnumeableTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var task = session.Query.All().Where(e => e.Value < 5 && e.Value > 0).AsEnumerable().AsAsync(); - Assert.That(task.IsCompleted, Is.True); + var result = await session.Query.All().Where(e => e.Value < 5 && e.Value > 0).AsEnumerable().AsAsync(); - int before = 1; - foreach (var value in await task) { + var before = 1; + foreach (var value in result) { Assert.That(value.Value, Is.EqualTo(before)); before++; } @@ -153,11 +152,10 @@ public async Task PersistentCollectionAsEnumerableTesk() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var container = session.Query.All().First(); - var task = container.EntitySet.Where(e => e.Value < 5 && e.Value > 0).AsEnumerable().AsAsync(); - Assert.That(task.IsCompleted, Is.True); + var result = await container.EntitySet.Where(e => e.Value < 5 && e.Value > 0).AsEnumerable().AsAsync(); - int before = 1; - foreach (var value in await task) { + var before = 1; + foreach (var value in result) { Assert.That(value.Value, Is.EqualTo(before)); before++; } @@ -169,11 +167,10 @@ public async Task DoQueryableTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var task = session.Query.All().Where(e => e.Value < 5 && e.Value > 0).AsAsync(); - Assert.That(task.IsCompleted, Is.False); + var result = await session.Query.All().Where(e => e.Value < 5 && e.Value > 0).AsAsync(); - int before = 1; - foreach (var value in await task) { + var before = 1; + foreach (var value in result) { Assert.That(value.Value, Is.EqualTo(before)); before++; } @@ -186,11 +183,10 @@ public async Task PersistentCollectionTest() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var container = session.Query.All().First(); - var task = container.EntitySet.Where(e => e.Value < 5 && e.Value > 0).AsAsync(); - Assert.That(task.IsCompleted, Is.False); + var result = await container.EntitySet.Where(e => e.Value < 5 && e.Value > 0).AsAsync(); - int before = 1; - foreach (var value in await task) { + var before = 1; + foreach (var value in result) { Assert.That(value.Value, Is.EqualTo(before)); before++; } @@ -203,11 +199,10 @@ public async Task DelayedQueryTest() using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var delayed = session.Query.ExecuteDelayed((q) => q.All().Where(e => e.Value < 5 && e.Value > 0)); - var task = delayed.AsAsync(); - Assert.That(task.IsCompleted, Is.False); + var task = await delayed.AsAsync(); - int before = 1; - foreach (var value in await task) { + var before = 1; + foreach (var value in task) { Assert.That(value.Value, Is.EqualTo(before)); before++; } @@ -217,8 +212,8 @@ public async Task DelayedQueryTest() private IEnumerable AsEnumerable(T a, T b, T c, T d) { yield return a; - int counter = 0; - while (counter < Int32.MaxValue/10000) { + var counter = 0; + while (counter < int.MaxValue/10000) { counter++; } yield return b; From f562e87752c75cb9ad4d926a43ca008a557cc4a0 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 18:58:17 +0500 Subject: [PATCH 28/71] Change unreal check in test 150 items sequence will never be equal to 170 items sequence :) --- .../Linq/Interfaces/AlphabetTest.cs | 80 ++++++++++++------- 1 file changed, 52 insertions(+), 28 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs index f99be05b1a..a12eb9674f 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs @@ -1,16 +1,17 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2003-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.09.24 using System; using System.Collections.Generic; +using System.Linq; using NUnit.Framework; +using Xtensive.Core; using Xtensive.Orm.Configuration; -using Xtensive.Orm.Tests.ObjectModel.Interfaces.Alphabet; -using System.Linq; using Xtensive.Orm.Providers; +using Xtensive.Orm.Tests.ObjectModel.Interfaces.Alphabet; namespace Xtensive.Orm.Tests.Linq.Interfaces { @@ -32,21 +33,23 @@ public override void TestFixtureSetUp() using (var session = Domain.OpenSession()) { using (var t = session.OpenTransaction()) { // ClassTable - for (int i = 0; i < EachCount; i++) - new A() {Name = "Name: A" + i}; - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { + _ = new A() {Name = "Name: A" + i}; + } + + for (var i = 0; i < EachCount; i++) { var named = (INamed)new B() { Name = "Name: B" + i, Tag = "Tag: B" + i}; named.Name = "Name: B'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var tagged = (ITagged)new C() { Name = "Name: C" + i }; tagged.Tag = "Tag: C'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var named = (INamed)new D() { Name = "Name: D" + i, Tag= "Tag: D" + i, First = "First: D" + i, Second = "Second: D" + i }; named.Name = "Name: D'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var named = (INamed)new E() { Name = "Name: E" + i, Tag = "Tag: E" + i, First = "First: E" + i, Second = "Second: E" + i }; var composite = (IComposite) named; named.Name = "Name: E'" + i; @@ -54,21 +57,23 @@ public override void TestFixtureSetUp() } // ConcreteTable - for (int i = 0; i < EachCount; i++) - new F() {Name = "Name: F" + i}; - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { + _ = new F() {Name = "Name: F" + i}; + } + + for (var i = 0; i < EachCount; i++) { var named = (INamed)new G() { Name = "Name: G" + i, Tag = "Tag: G" + i}; named.Name = "Name: G'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var tagged = (ITagged)new H() { Name = "Name: H" + i }; tagged.Tag = "Tag: H'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var named = (INamed)new I() { Name = "Name: I" + i, Tag= "Tag: I" + i, First = "First: I" + i, Second = "Second: I" + i }; named.Name = "Name: I'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var named = (INamed)new J() { Name = "Name: J" + i, Tag = "Tag: J" + i, First = "First: J" + i, Second = "Second: J" + i }; var composite = (IComposite) named; named.Name = "Name: J'" + i; @@ -76,21 +81,23 @@ public override void TestFixtureSetUp() } // SingleTable - for (int i = 0; i < EachCount; i++) - new K() {Name = "Name: K" + i}; - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { + _ = new K() {Name = "Name: K" + i}; + } + + for (var i = 0; i < EachCount; i++) { var named = (INamed)new L() { Name = "Name: L" + i, Tag = "Tag: L" + i}; named.Name = "Name: L'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var tagged = (ITagged)new M() { Name = "Name: M" + i }; tagged.Tag = "Tag: M'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var named = (INamed)new N() { Name = "Name: N" + i, Tag= "Tag: N" + i, First = "First: N" + i, Second = "Second: N" + i }; named.Name = "Name: N'" + i; } - for (int i = 0; i < EachCount; i++) { + for (var i = 0; i < EachCount; i++) { var named = (INamed)new O() { Name = "Name: O" + i, Tag = "Tag: O" + i, First = "First: O" + i, Second = "Second: O" + i }; var composite = (IComposite) named; named.Name = "Name: O'" + i; @@ -220,12 +227,29 @@ public void FetchTest() using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { + var key = Key.Create(Domain, 41L); var namedQuery = session.Query.All() - .Select(i => i.Name) - .OrderBy(i=>i) - .ToList(); - Assert.AreEqual(170, namedQuery.Count); - Assert.IsTrue(namedQuery.SequenceEqual(names)); + .Select(i => new { i.Key, i.Name}) + .OrderBy(i => i.Name) + .ToList(170); + Assert.AreEqual(170, namedQuery.Count); // some records are represented twice + + var groupByKey = namedQuery.GroupBy(i => i.Key, (a, b)=> new { Key = a, Items = b.ToList(2) }).ToList(150); + Assert.AreEqual(totalCount, groupByKey.Count); + + var abc = names.Zip(groupByKey, + (name, group) => new { + name1 = name, + name2 = group.Items.Count == 1 + ? group.Items[0].Name + : (group.Items[0].Name == name) + ? group.Items[0].Name + : group.Items[1].Name }); + + foreach(var anon in abc) { + Assert.AreEqual(anon.name1, anon.name2); + } + t.Complete(); } } From ccf3ce6c9e4ff92dc5e97333beaec36e85ade13e Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 19 Mar 2021 20:05:57 +0500 Subject: [PATCH 29/71] Tests improvements --- ...ueJira0537_DropDefaultConstraintBugTest.cs | 118 +++++++++--------- ...ldValidationTriggersLazyLoadFieldsFetch.cs | 59 ++++++--- 2 files changed, 104 insertions(+), 73 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs index f69f5d9c8d..c5e8405dab 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2014 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2013.12.30 @@ -256,18 +256,15 @@ public class AnotherArea : Entity public class Upgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; protected override void AddUpgradeHints(Collections.ISet hints) { - hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.StoredObject", typeof (WMS.StoredObject))); - hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.Area", typeof (Core.Area))); - hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.AnotherStoredObject", typeof (WMS.AnotherStoredObject))); - hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.AnotherArea", typeof (Core.AnotherArea))); - hints.Add(new ChangeFieldTypeHint(typeof (Core.AnotherArea), "NotEmpty")); + _ = hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.StoredObject", typeof(WMS.StoredObject))); + _ = hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.Area", typeof(Core.Area))); + _ = hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.AnotherStoredObject", typeof(WMS.AnotherStoredObject))); + _ = hints.Add(new RenameTypeHint("Xtensive.Orm.Tests.Issues.IssueJira0537_DropDefaultConstraintBugTestModel1.AnotherArea", typeof(Core.AnotherArea))); + _ = hints.Add(new ChangeFieldTypeHint(typeof(Core.AnotherArea), "NotEmpty")); } } } @@ -284,7 +281,6 @@ public class IssueJira0537_DropDefaultConstraintBugTest : AutoBuildTest private const string SpecialSchemaAlias = "dbo"; private ConnectionInfo connectionInfo; - private string connectionString; private static string multiDatabaseConnectionString; private static string singleDatabaseConnectionStringDatabase1; @@ -296,16 +292,13 @@ protected override void CheckRequirements() Require.AllFeaturesSupported(ProviderFeatures.Multidatabase); } - protected override void PopulateData() - { - BuildSingleDomain(Database1Name); - } + protected override void PopulateData() => BuildSingleDomain(Database1Name); [OneTimeSetUp] public override void TestFixtureSetUp() { - InitializeConnectionStrings(); CheckRequirements(); + InitializeConnectionStrings(); CleanUp(); PopulateData(); } @@ -318,52 +311,53 @@ public void MainTest() private static void BuildMultipleDomain(string coreDatabaseName, string wmsDatabaseName) { - var domainConfiguration = new DomainConfiguration(multiDatabaseConnectionString); + var domainConfiguration = new DomainConfiguration(multiDatabaseConnectionString) { + DefaultDatabase = WmsAlias, + DefaultSchema = SpecialSchemaAlias, + UpgradeMode = DomainUpgradeMode.PerformSafely + }; - domainConfiguration.DefaultDatabase = WmsAlias; - domainConfiguration.DefaultSchema = SpecialSchemaAlias; + var coreDatabase = new DatabaseConfiguration(CoreAlias) { + RealName = coreDatabaseName + }; - var coreDatabase = new DatabaseConfiguration(CoreAlias); - coreDatabase.RealName = coreDatabaseName; - - var wmsDatabase = new DatabaseConfiguration(WmsAlias); - wmsDatabase.RealName = wmsDatabaseName; + var wmsDatabase = new DatabaseConfiguration(WmsAlias) { + RealName = wmsDatabaseName + }; domainConfiguration.Databases.Add(coreDatabase); - - domainConfiguration.Databases.Add(wmsDatabase); - domainConfiguration.Types.Register(typeof (Model2.Upgrader).Assembly, typeof (Model2.Upgrader).Namespace); + domainConfiguration.Types.Register(typeof(Model2.Upgrader).Assembly, typeof(Model2.Upgrader).Namespace); - domainConfiguration.MappingRules.Map(typeof (Model2.Core.Area).Namespace).ToDatabase(CoreAlias); - domainConfiguration.MappingRules.Map(typeof (Model2.WMS.StoredObject).Namespace).ToDatabase(WmsAlias); - - domainConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; + domainConfiguration.MappingRules.Map(typeof(Model2.Core.Area).Namespace).ToDatabase(CoreAlias); + domainConfiguration.MappingRules.Map(typeof(Model2.WMS.StoredObject).Namespace).ToDatabase(WmsAlias); using (var domain = Domain.Build(domainConfiguration)) { } } private static void BuildSingleDomain(string wmsDatabaseName) { - var domainConfiguration = new DomainConfiguration(singleDatabaseConnectionStringDatabase1); - domainConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - domainConfiguration.DefaultSchema = SpecialSchemaAlias; - domainConfiguration.DefaultDatabase = WmsAlias; + var domainConfiguration = new DomainConfiguration(singleDatabaseConnectionStringDatabase1) { + UpgradeMode = DomainUpgradeMode.Recreate, + DefaultSchema = SpecialSchemaAlias, + DefaultDatabase = WmsAlias + }; - var wmsDatabase = new DatabaseConfiguration(WmsAlias); - wmsDatabase.RealName = wmsDatabaseName; + var wmsDatabase = new DatabaseConfiguration(WmsAlias) { + RealName = wmsDatabaseName + }; domainConfiguration.Databases.Add(wmsDatabase); domainConfiguration.MappingRules.Map(typeof (Model1.Area).Namespace).To(WmsAlias, SpecialSchemaAlias); - domainConfiguration.Types.Register(typeof (Model1.Area)); - domainConfiguration.Types.Register(typeof (Model1.StoredObject)); - domainConfiguration.Types.Register(typeof (Model1.AnotherArea)); - domainConfiguration.Types.Register(typeof (Model1.AnotherStoredObject)); + domainConfiguration.Types.Register(typeof(Model1.Area)); + domainConfiguration.Types.Register(typeof(Model1.StoredObject)); + domainConfiguration.Types.Register(typeof(Model1.AnotherArea)); + domainConfiguration.Types.Register(typeof(Model1.AnotherStoredObject)); - domainConfiguration.Databases.Add(wmsDatabaseName); + _ = domainConfiguration.Databases.Add(wmsDatabaseName); using (var domain = Domain.Build(domainConfiguration)) { } } @@ -392,14 +386,16 @@ private void ClearSchema(SqlDriver driver) foreach (var dropConstraintText in from foreignKeyInfo in foreignKeys from foreignKey in foreignKeyInfo.ForeignKeys select driver.Compile(SqlDdl.Alter(foreignKeyInfo.Table, SqlDdl.DropConstraint(foreignKey))).GetCommandText()) { - using (var command = connection.CreateCommand(dropConstraintText)) - command.ExecuteNonQuery(); + using (var command = connection.CreateCommand(dropConstraintText)) { + _ = command.ExecuteNonQuery(); + } } foreach (var table in schema.Tables) { var dropTableText = driver.Compile(SqlDdl.Drop(table, true)).GetCommandText(); - using (var command = connection.CreateCommand(dropTableText)) - command.ExecuteNonQuery(); + using (var command = connection.CreateCommand(dropTableText)) { + _ = command.ExecuteNonQuery(); + } } } finally { @@ -410,20 +406,24 @@ select driver.Compile(SqlDdl.Alter(foreignKeyInfo.Table, SqlDdl.DropConstraint(f private void InitializeConnectionStrings() { - var stringBuilder = new StringBuilder(); + connectionInfo = TestConfiguration.Instance.GetConnectionInfo(TestConfiguration.Instance.Storage); - stringBuilder.AppendFormat("{0}://", connectionInfo.ConnectionUrl.Protocol); - if (!string.IsNullOrEmpty(connectionInfo.ConnectionUrl.User) && !string.IsNullOrEmpty(connectionInfo.ConnectionUrl.Password)) - stringBuilder.AppendFormat("{0}:{1}@", connectionInfo.ConnectionUrl.User, connectionInfo.ConnectionUrl.Password); - stringBuilder.AppendFormat("{0}{1}", connectionInfo.ConnectionUrl.Host, (connectionInfo.ConnectionUrl.Port > 0) ? string.Format(":{0}", connectionInfo.ConnectionUrl.Port) : string.Empty); - stringBuilder.Append("/{0}{1}"); + var connectionUrl = connectionInfo.ConnectionUrl; + + var initialString = (!string.IsNullOrEmpty(connectionUrl.User) && !string.IsNullOrEmpty(connectionUrl.Password)) + ? string.Format("{0}://{1}:{2}@", connectionUrl.Protocol, connectionUrl.User, connectionUrl.Password) + : string.Format("{0}://", connectionUrl.Protocol); + + var stringBuilder = new StringBuilder(initialString) + .AppendFormat("{0}{1}", connectionUrl.Host, (connectionUrl.Port > 0) ? string.Format(":{0}", connectionUrl.Port) : string.Empty) + .Append("/{0}{1}"); + var paramsString = string.Empty; - foreach (var pair in connectionInfo.ConnectionUrl.Params) { - if (string.IsNullOrEmpty(paramsString)) - paramsString += string.Format("?{0}={1}", pair.Key, pair.Value); - else - paramsString += string.Format("&{0}={1}", pair.Key, pair.Value); + foreach (var pair in connectionUrl.Params) { + paramsString += string.IsNullOrEmpty(paramsString) + ? string.Format("?{0}={1}", pair.Key, pair.Value) + : string.Format("&{0}={1}", pair.Key, pair.Value); } singleDatabaseConnectionStringDatabase1 = string.Format(stringBuilder.ToString(), Database1Name, paramsString); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs index fb84471822..1f09e62d77 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2020 Xtensive LLC. +// Copyright (C) 2020-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -73,7 +73,11 @@ public class Chapter : Entity public class QueryCounter { - public int Count { get; private set; } + public int SelectCount { get; private set; } + + public int UpdateCount { get; private set; } + + public int OverallCount => SelectCount + UpdateCount; public Disposable Attach(Session session) { @@ -81,13 +85,25 @@ public Disposable Attach(Session session) return new Disposable((disposing) => session.Events.DbCommandExecuted -= Encount); } - public void Reset() => Count = 0; + public void Reset() => SelectCount = UpdateCount = 0; - private void Encount(object sender, DbCommandEventArgs eventArgs) => Count++; + private void Encount(object sender, DbCommandEventArgs eventArgs) + { + var text = eventArgs.Command.CommandText.Substring(0, 6); + if (text.Equals("SELECT", StringComparison.OrdinalIgnoreCase)) { + SelectCount++; + } + else if (text.Equals("UPDATE", StringComparison.OrdinalIgnoreCase)) { + UpdateCount++; + } + else { + throw new ArgumentOutOfRangeException("eventArgs.Command.CommandText"); + } + } public QueryCounter() { - Count = 0; + Reset(); } } } @@ -104,12 +120,15 @@ protected override DomainConfiguration BuildConfiguration() var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(Book).Assembly, typeof(Book).Namespace); configuration.UpgradeMode = DomainUpgradeMode.Recreate; + configuration.Sessions[WellKnown.Sessions.Default].BatchSize = 1; return configuration; } protected override void PopulateData() { - using (var session = Domain.OpenSession()) + var sessionConfig = new SessionConfiguration(SessionOptions.Default | SessionOptions.AutoActivation); + + using (var session = Domain.OpenSession(sessionConfig)) using (var transaction = session.OpenTransaction()) { var author = new Author() { FirstName = "Ivan", @@ -122,9 +141,9 @@ protected override void PopulateData() Author = author }; - new Chapter() { Title = "Chapter #1", Description = "Detailed description of Chapter #1", Owner = book }; - new Chapter() { Title = "Chapter #2", Description = "Detailed description of Chapter #2", Owner = book }; - new Chapter() { Title = "Chapter #3", Description = "Detailed description of Chapter #3", Owner = book }; + _ = new Chapter() { Title = "Chapter #1", Description = "Detailed description of Chapter #1", Owner = book }; + _ = new Chapter() { Title = "Chapter #2", Description = "Detailed description of Chapter #2", Owner = book }; + _ = new Chapter() { Title = "Chapter #3", Description = "Detailed description of Chapter #3", Owner = book }; oblomovKey = book.Key; goncharovKey = author.Key; @@ -144,7 +163,9 @@ public void LazyFieldHasNoConstraintTest() oblomov.Title = "Oblomov by Goncharov"; transaction.Complete(); } - Assert.That(counter.Count, Is.EqualTo(2)); + Assert.That(counter.OverallCount, Is.EqualTo(2)); + Assert.That(counter.SelectCount, Is.EqualTo(1)); + Assert.That(counter.UpdateCount, Is.EqualTo(1)); counter.Reset(); } } @@ -160,7 +181,9 @@ public void LazyFieldHasCheckAlwaysConstraintTest() goncharov.FirstName = goncharov.FirstName + "modified"; // should prefetch lazy load field transaction.Complete(); } - Assert.That(counter.Count, Is.EqualTo(3)); + Assert.That(counter.OverallCount, Is.EqualTo(3)); + Assert.That(counter.SelectCount, Is.EqualTo(2)); // 1 select + 1 fetch + Assert.That(counter.UpdateCount, Is.EqualTo(1)); counter.Reset(); } } @@ -177,12 +200,16 @@ public void LazyFieldHasCheckIfModifiedConstraintTest() } transaction.Complete(); } - Assert.That(counter.Count, Is.EqualTo(2)); + + Assert.That(counter.OverallCount, Is.EqualTo(4)); + Assert.That(counter.SelectCount, Is.EqualTo(1)); // select items only, no fetch + Assert.That(counter.UpdateCount, Is.EqualTo(3)); + counter.Reset(); } using (var session = Domain.OpenSession()) { - int updatedItems = 0; + var updatedItems = 0; using (counter.Attach(session)) using (var transaction = session.OpenTransaction()) { foreach(var chapter in session.Query.All()) { @@ -191,7 +218,11 @@ public void LazyFieldHasCheckIfModifiedConstraintTest() } transaction.Complete(); } - Assert.That(counter.Count, Is.EqualTo(5)); // query + fetches + update + + Assert.That(counter.OverallCount, Is.EqualTo(7)); + Assert.That(counter.SelectCount, Is.EqualTo(4)); // query + fetches + Assert.That(counter.UpdateCount, Is.EqualTo(3)); // updates + counter.Reset(); } } From d0d3a5f960b4c8207cdd183d72aa918afc036f3f Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 22 Mar 2021 17:29:05 +0500 Subject: [PATCH 30/71] Sqlite: use string parameter with formatter instead datetime Since there is no native support for datetime and we use strftime we can use strings. it also fixes some cases, for intance, work of groupby --- .../Sql.Drivers.Sqlite/v3/TypeMapper.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs b/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs index 86205567d5..129a4e6911 100644 --- a/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs +++ b/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Malisa Ncube // Created: 2011.04.29 @@ -19,6 +19,7 @@ internal class TypeMapper : Sql.TypeMapper private ValueRange dateTimeOffsetRange; private const string DateTimeOffsetFormat = "yyyy-MM-dd HH:mm:ss.fffK"; + private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; public override object ReadBoolean(DbDataReader reader, int index) { @@ -58,9 +59,13 @@ public override void BindULong(DbParameter parameter, object value) public override void BindDateTime(DbParameter parameter, object value) { - if (value!=null) - value = ValueRangeValidator.Correct((DateTime) value, dateTimeRange); - base.BindDateTime(parameter, value); + parameter.DbType = DbType.String; + if (value == null) { + parameter.Value = DBNull.Value; + return; + } + var correctValue = ValueRangeValidator.Correct((DateTime) value, dateTimeRange); + parameter.Value = correctValue.ToString(DateTimeFormat, CultureInfo.InvariantCulture); } public override void BindDateTimeOffset(DbParameter parameter, object value) From 8c8ea56ffe89803e08c7d2359fea02a0971aadbd Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 22 Mar 2021 19:38:58 +0500 Subject: [PATCH 31/71] Oracle: interval precision increse for literal values We use INTERVAL DAYS TO SECOND for columns which is equivalent to INTERVAL DAYS(2) TO SECOND(6). But for liternal values had less precision which is not good idea. --- .../Sql.Drivers.Oracle/v11/Translator.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs index ee9f2e7bb3..9e13782bac 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 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 // Created: 2009.07.17 @@ -11,6 +11,14 @@ namespace Xtensive.Sql.Drivers.Oracle.v11 { internal class Translator : v10.Translator { + public override string Translate(SqlValueType type) + { + // we need to explicitly specify maximum interval precision + if (type.Type == SqlType.Interval) + return "INTERVAL DAY(6) TO SECOND(6)"; + return base.Translate(type); + } + // Constructors public Translator(SqlDriver driver) From fc60c25f125d87b44d831e5010f61149df239158 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 23 Mar 2021 11:59:04 +0500 Subject: [PATCH 32/71] Workaround for oracle specifig begining of queries + missing requirement --- ..._InOperationDoesNotCreateTemporaryTable.cs | 46 ++++++++----------- ...ldValidationTriggersLazyLoadFieldsFetch.cs | 6 +-- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0570_InOperationDoesNotCreateTemporaryTable.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0570_InOperationDoesNotCreateTemporaryTable.cs index 1372e05aa2..50e1c35ec1 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0570_InOperationDoesNotCreateTemporaryTable.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0570_InOperationDoesNotCreateTemporaryTable.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.08.24 @@ -374,7 +374,7 @@ public void StoreThenIncludeTest() var businessUnitIds = session.Query.All().Select(bu=>bu.Id).ToList(); var bounds = new Tuple[26]; - for (int i = 0; i < bounds.Length; i++) { + for (var i = 0; i < bounds.Length; i++) { bounds[i] = new Tuple(DateTime.UtcNow, DateTime.UtcNow, ""); } var list = session.Query.All() @@ -393,7 +393,7 @@ public void IncludeThenStoreTest() var businessUnitIds = session.Query.All().Select(bu => bu.Id).ToList(); var bounds = new Tuple[26]; - for (int i = 0; i < bounds.Length; i++) { + for (var i = 0; i < bounds.Length; i++) { bounds[i] = new Tuple(DateTime.UtcNow, DateTime.UtcNow, ""); } var list = session.Query.All() @@ -412,7 +412,7 @@ public void IncludeWithoutStoreTest() var businessUnitIds = session.Query.All().Select(bu => bu.Id).ToList(); var bounds = new Tuple[26]; - for (int i = 0; i < bounds.Length; i++) { + for (var i = 0; i < bounds.Length; i++) { bounds[i] = new Tuple(DateTime.UtcNow, DateTime.UtcNow, ""); } var list = session.Query.All() @@ -424,12 +424,13 @@ public void IncludeWithoutStoreTest() [Test] public void StoreWithoutIncludeTest() { + Require.AllFeaturesSupported(ProviderFeatures.TemporaryTables); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var businessUnitIds = session.Query.All().Select(bu => bu.Id).ToList(); var bounds = new Tuple[26]; - for (int i = 0; i < bounds.Length; i++) { + for (var i = 0; i < bounds.Length; i++) { bounds[i] = new Tuple(DateTime.UtcNow, DateTime.UtcNow, ""); } var list = session.Query.All() @@ -505,15 +506,16 @@ private void PopulateEnums() private void PopulateCustomers() { customerIds = new int[160]; - for (int i = 0; i < 160; i++) + for (var i = 0; i < 160; i++) { customerIds[i] = new Customer().Id; + } } private void PopulateInvoices() { foreach (var customer in Query.All()) { foreach (var status in Enum.GetValues(typeof(InvoiceStatus))) { - new Invoice { + _ = new Invoice { Active = true, Customer = customer, InvoicedOn = DateTime.Now, @@ -527,7 +529,7 @@ private void PopulatePayments() { var generator = new Random(); foreach (var invoice in Query.All().Where(el => el.Status.In(queryableInvoiceStatuses))) { - new Payment { + _ = new Payment { Active = true, Amount = new decimal(generator.Next(10000000, 200000000) / 100000), Invoice = invoice, @@ -538,26 +540,18 @@ private void PopulatePayments() private void PopulateBusinessUnits() { - new BusinessUnit() { - Active = true, - QuickbooksClass = "" - }; - - new BusinessUnit() { - Active = true, - QuickbooksClass = "" - }; - - new BusinessUnit() { - Active = true, - QuickbooksClass = "" - }; + for(var i = 0; i < 3; i++) { + _ = new BusinessUnit() { + Active = true, + QuickbooksClass = "" + }; + } } private void PopulateJobs() { foreach (var bu in Query.All()) { - new Job() { + _ = new Job() { BusinessUnit = bu }; } @@ -585,7 +579,7 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (Payment).Assembly, typeof (Payment).Namespace); + configuration.Types.Register(typeof(Payment).Assembly, typeof(Payment).Namespace); return configuration; } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs index 1f09e62d77..50a49ff183 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0793_FieldValidationTriggersLazyLoadFieldsFetch.cs @@ -89,11 +89,11 @@ public Disposable Attach(Session session) private void Encount(object sender, DbCommandEventArgs eventArgs) { - var text = eventArgs.Command.CommandText.Substring(0, 6); - if (text.Equals("SELECT", StringComparison.OrdinalIgnoreCase)) { + var text = eventArgs.Command.CommandText.Substring(0, 30); + if (text.Contains("SELECT", StringComparison.OrdinalIgnoreCase)) { SelectCount++; } - else if (text.Equals("UPDATE", StringComparison.OrdinalIgnoreCase)) { + else if (text.Contains("UPDATE", StringComparison.OrdinalIgnoreCase)) { UpdateCount++; } else { From 2edb542f916eb707a3613adcf1f50ae629d17a5a Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 23 Mar 2021 13:37:24 +0500 Subject: [PATCH 33/71] Sqlite: increase fractions in datetime format --- Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs b/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs index 129a4e6911..900b64d8c9 100644 --- a/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs +++ b/Orm/Xtensive.Orm.Sqlite/Sql.Drivers.Sqlite/v3/TypeMapper.cs @@ -19,7 +19,7 @@ internal class TypeMapper : Sql.TypeMapper private ValueRange dateTimeOffsetRange; private const string DateTimeOffsetFormat = "yyyy-MM-dd HH:mm:ss.fffK"; - private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; + private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fffffff"; public override object ReadBoolean(DbDataReader reader, int index) { From 3c6f503df13e7da3cff88aebde379848cbb35d56 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 23 Mar 2021 17:21:53 +0500 Subject: [PATCH 34/71] FirstSingleTest: Separate test case for SQLite SQLite allows to have more than one row in result of subquery which is a column of main query --- Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs b/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs index 202a80cebc..121b007fcc 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/FirstSingleTest.cs @@ -9,6 +9,7 @@ using NUnit.Framework; using Xtensive.Orm.Tests; using Xtensive.Orm.Linq; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.ObjectModel; using Xtensive.Orm.Tests.ObjectModel.ChinookDO; @@ -213,6 +214,16 @@ public void SubquerySingleTest() Assert.AreEqual(customersCount, list.Count); } + [Test] + public void SubquerySingleSQLiteTest() + { + Require.ProviderIs(StorageProvider.Sqlite, "SQLite allows to have more that one row in result of subquery that represents column."); + var customersCount = Session.Query.All().Count(c => c.Invoices.Count > 0); + var result = Session.Query.All().Where(c => c.Invoices.Count > 0).Select(c => c.Invoices.Single()); + var list = result.ToList(); + Assert.AreEqual(customersCount, list.Count); + } + [Test] public void SubquerySingleExpectedException1Test() { @@ -224,7 +235,7 @@ public void SubquerySingleExpectedException1Test() [Test] public void SubquerySingleExpectedException2Test() { - Require.ProviderIsNot(StorageProvider.SqlServerCe); + Require.ProviderIsNot(StorageProvider.SqlServerCe | StorageProvider.Sqlite); var exceptionThrown = false; var result = Session.Query.All().Where(c => c.Invoices.Count > 0).Select(c => c.Invoices.Single()); try { From c2fab5554ab20d5a5ed5638ef3b2c673c822ac5a Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 24 Mar 2021 20:10:50 +0500 Subject: [PATCH 35/71] Firebird improvements Correct datetime forman string and column default value extraction fix --- .../Sql.Drivers.Firebird/Constants.cs | 9 ++++--- .../Sql.Drivers.Firebird/v2_5/Extractor.cs | 25 ++++++++++++------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Constants.cs b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Constants.cs index 6b3fe68949..d0c47590a5 100644 --- a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Constants.cs +++ b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/Constants.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Csaba Beer // Created: 2011.01.08 @@ -12,6 +12,7 @@ internal static class Constants { public const string DefaultSchemaName = ""; // "Firebird"; - public const string DateTimeFormatString = @"''\'yyyy\.MM\.dd HH\:mm\:ss\:FFF\'''"; + // cannot use "FFF" cause it may lead to empty string for fractions part. + public const string DateTimeFormatString = @"''\'yyyy\.MM\.dd HH\:mm\:ss\.fff\'''"; } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Extractor.cs b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Extractor.cs index faf0f904e9..d5a97c08d7 100644 --- a/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Extractor.cs +++ b/Orm/Xtensive.Orm.Firebird/Sql.Drivers.Firebird/v2_5/Extractor.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Csaba Beer // Created: 2011.01.13 @@ -84,11 +84,10 @@ private void ExtractTables() private void ExtractTableColumns() { - using ( - var reader = Connection.CreateCommand(GetExtractTableColumnsQuery()).ExecuteReader(CommandBehavior.SingleResult) - ) { + using (var command = Connection.CreateCommand(GetExtractTableColumnsQuery())) + using (var reader = command.ExecuteReader(CommandBehavior.SingleResult)) { Table table = null; - int lastColumnId = int.MaxValue; + var lastColumnId = int.MaxValue; while (reader.Read()) { int columnSeq = reader.GetInt16(2); if (columnSeq <= lastColumnId) { @@ -99,8 +98,16 @@ private void ExtractTableColumns() column.DataType = CreateValueType(reader, 4, 5, 7, 8, 9); column.IsNullable = ReadBool(reader, 10); var defaultValue = ReadStringOrNull(reader, 11); - if (!string.IsNullOrEmpty(defaultValue)) - column.DefaultValue = SqlDml.Native(defaultValue); + if (!string.IsNullOrEmpty(defaultValue)) { + defaultValue = defaultValue.TrimStart(' '); + if (defaultValue.StartsWith("DEFAULT", StringComparison.OrdinalIgnoreCase)) { + defaultValue = defaultValue.Substring(7).TrimStart(' '); + } + if (!string.IsNullOrEmpty(defaultValue)) { + column.DefaultValue = SqlDml.Native(defaultValue); + } + } + lastColumnId = columnSeq; } } From 30b93294cb8511d49930755d2d58c5cf9a5795e4 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 24 Mar 2021 20:12:25 +0500 Subject: [PATCH 36/71] Workaround for firebird sequence behavior in test --- .../Upgrade/DomainUpgradeTest.cs | 634 ++++++++++-------- 1 file changed, 346 insertions(+), 288 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs index b08d5e9afe..487ce5a55e 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Ivan Galkin // Created: 2009.05.20 @@ -52,66 +52,122 @@ public void SetUp() BuildDomain("1", DomainUpgradeMode.Recreate); FillData(); } - + + [TearDown] + public void TearDown() + { + domain.DisposeSafely(); + } + [Test] public void UpgradeModeTest() { - BuildDomain("1", DomainUpgradeMode.Recreate, null, typeof (Address), typeof (Person)); + BuildDomain("1", DomainUpgradeMode.Recreate, null, typeof(Address), typeof(Person)); - BuildDomain("1", DomainUpgradeMode.PerformSafely, null, typeof (Address), typeof (Person), typeof (BusinessContact)); + BuildDomain("1", DomainUpgradeMode.PerformSafely, null, typeof(Address), typeof(Person), typeof(BusinessContact)); AssertEx.Throws(() => - BuildDomain("1", DomainUpgradeMode.PerformSafely, null, typeof (Address), typeof (Person))); + BuildDomain("1", DomainUpgradeMode.PerformSafely, null, typeof(Address), typeof(Person))); - BuildDomain("1", DomainUpgradeMode.Validate, null, typeof (Address), typeof (Person), typeof (BusinessContact)); + BuildDomain("1", DomainUpgradeMode.Validate, null, typeof(Address), typeof(Person), typeof(BusinessContact)); AssertEx.Throws(() => - BuildDomain("1", DomainUpgradeMode.Validate, null, typeof (Address), typeof (Person))); + BuildDomain("1", DomainUpgradeMode.Validate, null, typeof(Address), typeof(Person))); AssertEx.Throws(() => - BuildDomain("1", DomainUpgradeMode.Validate, null, typeof (Address), typeof (Person), - typeof (BusinessContact), typeof (Employee), typeof (Order))); + BuildDomain("1", DomainUpgradeMode.Validate, null, typeof(Address), typeof(Person), + typeof(BusinessContact), typeof(Employee), typeof(Order))); } [Test] public void UpgradeGeneratorsTest() { + Require.ProviderIsNot(StorageProvider.Firebird); Require.AnyFeatureSupported(ProviderFeatures.Sequences | ProviderFeatures.ArbitraryIdentityIncrement); var generatorCacheSize = 3; - BuildDomain("1", DomainUpgradeMode.Recreate, generatorCacheSize, typeof (Address), typeof (Person)); - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - for (int i = 0; i < generatorCacheSize; i++) - new Person { - Address = new Address {City = "City", Country = "Country"} - }; - Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 4); - Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 3); - t.Complete(); + BuildDomain("1", DomainUpgradeMode.Recreate, generatorCacheSize, typeof(Address), typeof(Person)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + for (var i = 0; i < generatorCacheSize; i++) { + _ = new Person { + Address = new Address { City = "City", Country = "Country" } + }; } + + Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 4); + Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 3); + t.Complete(); } - BuildDomain("1", DomainUpgradeMode.Perform, generatorCacheSize, typeof (Address), typeof (Person)); - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - for (int i = 0; i < generatorCacheSize; i++) - new Person { - Address = new Address {City = "City", Country = "Country"} - }; - Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 8); - Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 6); - t.Complete(); + + BuildDomain("1", DomainUpgradeMode.Perform, generatorCacheSize, typeof(Address), typeof(Person)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + for (var i = 0; i < generatorCacheSize; i++) { + _ = new Person { + Address = new Address { City = "City", Country = "Country" } + }; } + + Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 8); + Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 6); + t.Complete(); } - + generatorCacheSize = 2; - BuildDomain("1", DomainUpgradeMode.Perform, generatorCacheSize, typeof (Address), typeof (Person)); - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - new Person {Address = new Address {City = "City", Country = "Country"}}; - new Person {Address = new Address {City = "City", Country = "Country"}}; - new Person {Address = new Address {City = "City", Country = "Country"}}; - Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 13); - Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 12); - t.Complete(); + BuildDomain("1", DomainUpgradeMode.Perform, generatorCacheSize, typeof(Address), typeof(Person)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + _ = new Person { Address = new Address { City = "City", Country = "Country" } }; + _ = new Person { Address = new Address { City = "City", Country = "Country" } }; + _ = new Person { Address = new Address { City = "City", Country = "Country" } }; + Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 13); + Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 12); + t.Complete(); + } + } + + [Test] + public void UpgradeGeneratorsFirebirdTest() + { + Require.ProviderIs(StorageProvider.Firebird); + + var generatorCacheSize = 3; + BuildDomain("1", DomainUpgradeMode.Recreate, generatorCacheSize, typeof(Address), typeof(Person)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + for (var i = 0; i < generatorCacheSize; i++) { + _ = new Person { + Address = new Address { City = "City", Country = "Country" } + }; } + + Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 4); + Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 3); + t.Complete(); + } + + BuildDomain("1", DomainUpgradeMode.Perform, generatorCacheSize, typeof(Address), typeof(Person)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + for (var i = 0; i < generatorCacheSize; i++) { + _ = new Person { + Address = new Address { City = "City", Country = "Country" } + }; + } + + Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 8); + Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 6); + t.Complete(); + } + + generatorCacheSize = 2;// ignored because Firebird sequences has no increment support + BuildDomain("1", DomainUpgradeMode.Perform, generatorCacheSize, typeof(Address), typeof(Person)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + _ = new Person { Address = new Address { City = "City", Country = "Country" } }; + _ = new Person { Address = new Address { City = "City", Country = "Country" } }; + _ = new Person { Address = new Address { City = "City", Country = "Country" } }; + Assert.LessOrEqual(session.Query.All().Max(p => p.Id), 10); + Assert.GreaterOrEqual(session.Query.All().Max(p => p.Id), 9); + t.Complete(); } } @@ -121,26 +177,25 @@ public void UpdateTypeIdTest() int personTypeId; int maxTypeId; - BuildDomain("1", DomainUpgradeMode.Recreate, null, typeof (Address), typeof (Person)); - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - personTypeId = session.Query.All() - .First(type => type.Name=="Xtensive.Orm.Tests.Upgrade.Model.Version1.Person").Id; - maxTypeId = session.Query.All().Max(type => type.Id); - } + BuildDomain("1", DomainUpgradeMode.Recreate, null, typeof(Address), typeof(Person)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + personTypeId = session.Query.All() + .First(type => type.Name == "Xtensive.Orm.Tests.Upgrade.Model.Version1.Person").Id; + maxTypeId = session.Query.All().Max(type => type.Id); } - BuildDomain("1", DomainUpgradeMode.PerformSafely, null, typeof (Address), typeof (Person), typeof (BusinessContact)); - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var businessContactTypeId = session.Query.All() - .First(type => type.Name=="Xtensive.Orm.Tests.Upgrade.Model.Version1.BusinessContact").Id; - var newPersonTypeId = session.Query.All() - .First(type => type.Name=="Xtensive.Orm.Tests.Upgrade.Model.Version1.Person").Id; + BuildDomain("1", DomainUpgradeMode.PerformSafely, null, typeof(Address), typeof(Person), typeof(BusinessContact)); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var businessContactTypeId = session.Query.All() + .First(type => type.Name == "Xtensive.Orm.Tests.Upgrade.Model.Version1.BusinessContact").Id; + var newPersonTypeId = session.Query.All() + .First(type => type.Name == "Xtensive.Orm.Tests.Upgrade.Model.Version1.Person").Id; + + Assert.AreEqual(personTypeId, newPersonTypeId); + Assert.AreEqual(maxTypeId + 1, businessContactTypeId); - Assert.AreEqual(personTypeId, newPersonTypeId); - Assert.AreEqual(maxTypeId + 1, businessContactTypeId); - } } } @@ -151,27 +206,25 @@ public void UpdateTypeIdWithMutualRenameTest() int personTypeId; int businessContactTypeId; - - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - personTypeId = session.Query.All() - .First(type => type.Name=="Xtensive.Orm.Tests.Upgrade.Model.Version1.Person").Id; - businessContactTypeId = session.Query.All() - .First(type => type.Name=="Xtensive.Orm.Tests.Upgrade.Model.Version1.BusinessContact").Id; - } + + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + personTypeId = session.Query.All() + .First(type => type.Name == "Xtensive.Orm.Tests.Upgrade.Model.Version1.Person").Id; + businessContactTypeId = session.Query.All() + .First(type => type.Name == "Xtensive.Orm.Tests.Upgrade.Model.Version1.BusinessContact").Id; } BuildDomain("2", DomainUpgradeMode.Perform); - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var newBusinessContactTypeId = session.Query.All() - .First(type => type.Name=="Xtensive.Orm.Tests.Upgrade.Model.Version2.BusinessContact").Id; - var newPersonTypeId = session.Query.All() - .First(type => type.Name=="Xtensive.Orm.Tests.Upgrade.Model.Version2.Person").Id; - - Assert.AreEqual(personTypeId, newBusinessContactTypeId); - Assert.AreEqual(businessContactTypeId, newPersonTypeId); - } + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var newBusinessContactTypeId = session.Query.All() + .First(type => type.Name == "Xtensive.Orm.Tests.Upgrade.Model.Version2.BusinessContact").Id; + var newPersonTypeId = session.Query.All() + .First(type => type.Name == "Xtensive.Orm.Tests.Upgrade.Model.Version2.Person").Id; + + Assert.AreEqual(personTypeId, newBusinessContactTypeId); + Assert.AreEqual(businessContactTypeId, newPersonTypeId); } } @@ -181,94 +234,95 @@ public void UpgradeToVersion2Test() Require.ProviderIsNot(StorageProvider.Firebird); BuildDomain("2", DomainUpgradeMode.Perform); - using (var session = domain.OpenSession()) { - using (session.OpenTransaction()) { - Assert.AreEqual(2, session.Query.All().Count()); - Assert.AreEqual("Island Trading", session.Query.All() - .First(person => person.ContactName=="Helen Bennett").CompanyName); - Assert.AreEqual(5, session.Query.All().Count()); - Assert.AreEqual("Suyama", session.Query.All() - .First(contact => contact.FirstName=="Michael").LastName); - Assert.AreEqual("Fuller", session.Query.All() - .First(employee => employee.FirstName=="Nancy").ReportsTo.LastName); - Assert.AreEqual(123, session.Query.All() - .First(person => person.ContactName=="Helen Bennett").PassportNumber); - Assert.AreEqual(1, session.Query.All() - .First(order => order.ProductName=="Maxilaku").Number); - - session.Query.All().Single(product => product.Title=="DataObjects.NET"); - session.Query.All().Single(product => product.Title=="HelpServer"); - Assert.AreEqual(2, session.Query.All().Count()); - var webApps = session.Query.All().Single(group => group.Name=="Web applications"); - var frameworks = session.Query.All().Single(group => group.Name=="Frameworks"); - Assert.AreEqual(1, webApps.Products.Count); - Assert.AreEqual(1, frameworks.Products.Count); - - var allBoys = session.Query.All().ToArray(); - var allGirls = session.Query.All().ToArray(); - Assert.AreEqual(2, allBoys.Length); - Assert.AreEqual(2, allGirls.Length); - var alex = allBoys.Single(boy => boy.Name=="Alex"); - foreach (var girl in allGirls) - Assert.IsTrue(alex.MeetWith.Contains(girl)); - - var e1 = session.Query.All().Single(); - var e2 = session.Query.All().Single(); - var e3 = session.Query.All().Single(); - var e4 = session.Query.All().Single(); - var se1 = session.Query.All().Single(); - var se2 = session.Query.All().Single(); - var se3 = session.Query.All().Single(); - var se4 = session.Query.All().Single(); - - Assert.AreEqual(1, e1.Code); - Assert.AreEqual(2, e2.Code); - Assert.AreEqual(3, e3.Code); - Assert.AreEqual(4, e4.Code); - - Assert.AreEqual(e1, e2.E1); - Assert.AreEqual(e2, e3.E2); - Assert.AreEqual(e3, e4.E3); - - Assert.AreEqual(se1.S1.MyE1, e1); - - Assert.AreEqual(se2.S2.MyE2, e2); - Assert.AreEqual(se2.S2.S1.MyE1, e1); - - Assert.AreEqual(se3.S3.MyE3, e3); - Assert.AreEqual(se3.S3.S2.MyE2, e2); - Assert.AreEqual(se3.S3.S2.S1.MyE1, e1); - - Assert.AreEqual(se4.S4.MyE4, e4); - Assert.AreEqual(se4.S4.S3.MyE3, e3); - Assert.AreEqual(se4.S4.S3.S2.MyE2, e2); - Assert.AreEqual(se4.S4.S3.S2.S1.MyE1, e1); - - var so1 = session.Query.All().Single(e => e.Id==0); - var so2 = session.Query.All().Single(e => e.Id==1); - var re1 = session.Query.All().Single(e => e.A==1 && e.B==2); - var re2 = session.Query.All().Single(e => e.A==2 && e.B==3); - if (!IncludeTypeIdModifier.IsEnabled) { - Assert.AreEqual(so1.Reference, re1); - Assert.AreEqual(so2.Reference, re2); - } - - Assert.AreEqual(2, session.Query.All>().Count()); - Assert.AreEqual("Alex", session.Query.All>().First().NewRoot.Name); + using (var session = domain.OpenSession()) + using (session.OpenTransaction()) { + Assert.AreEqual(2, session.Query.All().Count()); + Assert.AreEqual("Island Trading", session.Query.All() + .First(person => person.ContactName == "Helen Bennett").CompanyName); + Assert.AreEqual(5, session.Query.All().Count()); + Assert.AreEqual("Suyama", session.Query.All() + .First(contact => contact.FirstName == "Michael").LastName); + Assert.AreEqual("Fuller", session.Query.All() + .First(employee => employee.FirstName == "Nancy").ReportsTo.LastName); + Assert.AreEqual(123, session.Query.All() + .First(person => person.ContactName == "Helen Bennett").PassportNumber); + Assert.AreEqual(1, session.Query.All() + .First(order => order.ProductName == "Maxilaku").Number); + + _ = session.Query.All().Single(product => product.Title == "DataObjects.NET"); + _ = session.Query.All().Single(product => product.Title == "HelpServer"); + Assert.AreEqual(2, session.Query.All().Count()); + var webApps = session.Query.All().Single(group => group.Name == "Web applications"); + var frameworks = session.Query.All().Single(group => group.Name == "Frameworks"); + Assert.AreEqual(1, webApps.Products.Count); + Assert.AreEqual(1, frameworks.Products.Count); + + var allBoys = session.Query.All().ToArray(); + var allGirls = session.Query.All().ToArray(); + Assert.AreEqual(2, allBoys.Length); + Assert.AreEqual(2, allGirls.Length); + var alex = allBoys.Single(boy => boy.Name == "Alex"); + foreach (var girl in allGirls) { + Assert.IsTrue(alex.MeetWith.Contains(girl)); + } + + var e1 = session.Query.All().Single(); + var e2 = session.Query.All().Single(); + var e3 = session.Query.All().Single(); + var e4 = session.Query.All().Single(); + var se1 = session.Query.All().Single(); + var se2 = session.Query.All().Single(); + var se3 = session.Query.All().Single(); + var se4 = session.Query.All().Single(); + + Assert.AreEqual(1, e1.Code); + Assert.AreEqual(2, e2.Code); + Assert.AreEqual(3, e3.Code); + Assert.AreEqual(4, e4.Code); + + Assert.AreEqual(e1, e2.E1); + Assert.AreEqual(e2, e3.E2); + Assert.AreEqual(e3, e4.E3); + + Assert.AreEqual(se1.S1.MyE1, e1); + + Assert.AreEqual(se2.S2.MyE2, e2); + Assert.AreEqual(se2.S2.S1.MyE1, e1); + + Assert.AreEqual(se3.S3.MyE3, e3); + Assert.AreEqual(se3.S3.S2.MyE2, e2); + Assert.AreEqual(se3.S3.S2.S1.MyE1, e1); + + Assert.AreEqual(se4.S4.MyE4, e4); + Assert.AreEqual(se4.S4.S3.MyE3, e3); + Assert.AreEqual(se4.S4.S3.S2.MyE2, e2); + Assert.AreEqual(se4.S4.S3.S2.S1.MyE1, e1); + + var so1 = session.Query.All().Single(e => e.Id == 0); + var so2 = session.Query.All().Single(e => e.Id == 1); + var re1 = session.Query.All().Single(e => e.A == 1 && e.B == 2); + var re2 = session.Query.All().Single(e => e.A == 2 && e.B == 3); + if (!IncludeTypeIdModifier.IsEnabled) { + Assert.AreEqual(so1.Reference, re1); + Assert.AreEqual(so2.Reference, re2); } + + Assert.AreEqual(2, session.Query.All>().Count()); + Assert.AreEqual("Alex", session.Query.All>().First().NewRoot.Name); } } private void BuildDomain(string version, DomainUpgradeMode upgradeMode) { - if (domain!=null) + if (domain!=null) { domain.DisposeSafely(); + } var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = upgradeMode; configuration.Types.Register(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Upgrade.Model.Version" + version); - configuration.Types.Register(typeof (Upgrader)); + configuration.Types.Register(typeof(Upgrader)); using (Upgrader.Enable(version)) { domain = Domain.Build(configuration); } @@ -276,15 +330,20 @@ private void BuildDomain(string version, DomainUpgradeMode upgradeMode) private void BuildDomain(string version, DomainUpgradeMode upgradeMode, int? keyCacheSize, params Type[] types) { - if (domain != null) + if (domain != null) { domain.DisposeSafely(); + } var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = upgradeMode; - foreach (var type in types) + foreach (var type in types) { configuration.Types.Register(type); - if (keyCacheSize.HasValue) + } + + if (keyCacheSize.HasValue) { configuration.KeyGeneratorCacheSize = keyCacheSize.Value; + } + configuration.Types.Register(typeof (Upgrader)); using (Upgrader.Enable(version)) { domain = Domain.Build(configuration); @@ -295,139 +354,138 @@ private void BuildDomain(string version, DomainUpgradeMode upgradeMode, int? key private void FillData() { - using (var session = domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - // BusinessContacts - var helen = new BusinessContact { - Address = new Address { - City = "Cowes", - Country = "UK" - }, - CompanyName = "Island Trading", - ContactName = "Helen Bennett", - PassportNumber = "123" - }; - var philip = new BusinessContact { - Address = new Address { - City = "Brandenburg", - Country = "Germany" - }, - CompanyName = "Koniglich Essen", - ContactName = "Philip Cramer", - PassportNumber = "321" - }; - - // Employies - var director = new Employee { - Address = new Address { - City = "Tacoma", - Country = "USA" - }, - FirstName = "Andrew", - LastName = "Fuller", - HireDate = new DateTime(1992, 8, 13) - }; - var nancy = new Employee { - Address = new Address { - City = "Seattle", - Country = "USA" - }, - FirstName = "Nancy", - LastName = "Davolio", - HireDate = new DateTime(1992, 5, 1), - ReportsTo = director - }; - var michael = new Employee { - Address = new Address { - City = "London", - Country = "UK" - }, - FirstName = "Michael", - LastName = "Suyama", - HireDate = new DateTime(1993, 10, 17), - ReportsTo = director - }; - - // Orders - new Order { - OrderNumber = "1", - Customer = helen, - Employee = michael, - Freight = 12, - OrderDate = new DateTime(1996, 7, 4), - ProductName = "Maxilaku" - }; - new Order { - OrderNumber = "2", - Customer = helen, - Employee = nancy, - Freight = 12, - OrderDate = new DateTime(1996, 7, 4), - ProductName = "Filo Mix" - }; - new Order { - OrderNumber = "3", - Customer = philip, - Employee = michael, - Freight = 12, - OrderDate = new DateTime(1996, 7, 4), - ProductName = "Tourtiere" - }; - new Order { - OrderNumber = "4", - Customer = philip, - Employee = nancy, - Freight = 12, - OrderDate = new DateTime(1996, 7, 4), - ProductName = "Pate chinois" - }; - - // Products & catgories - new Category { - Name = "Web applications", - Products = {new Model.Version1.Product {Name = "HelpServer", IsActive = true}} - }; - - new Category { - Name = "Frameworks", - Products = {new Model.Version1.Product {Name = "DataObjects.NET", IsActive = true}} - }; - - // Boys & girls - var alex = new Model.Version1.Boy("Alex"); - var dmitry = new Model.Version1.Boy("Dmitry"); - var elena = new Model.Version1.Girl("Elena"); - var tanya = new Model.Version1.Girl("Tanya"); - alex.FriendlyGirls.Add(elena); - alex.FriendlyGirls.Add(tanya); - elena.FriendlyBoys.Add(dmitry); - - // EntityX - var e1 = new Model.Version1.Entity1(1); - var e2 = new Model.Version1.Entity2(2, e1); - var e3 = new Model.Version1.Entity3(3, e2); - var e4 = new Model.Version1.Entity4(4, e3); - - // StructureContainerX - var se1 = new Model.Version1.StructureContainer1 {S1 = new Structure1 {E1 = e1}}; - var se2 = new Model.Version1.StructureContainer2 {S2 = new Structure2 {E2 = e2, S1 = se1.S1}}; - var se3 = new Model.Version1.StructureContainer3 {S3 = new Structure3 {E3 = e3, S2 = se2.S2}}; - var se4 = new Model.Version1.StructureContainer4 {S4 = new Structure4 {E4 = e4, S3 = se3.S3}}; - - // MyStructureOwner, ReferencedEntity - new Model.Version1.MyStructureOwner(0) {Structure = new MyStructure {A = 1, B = 2}}; - new Model.Version1.MyStructureOwner(1) {Structure = new MyStructure {A = 2, B = 3}}; - new Model.Version1.ReferencedEntity(1, 2); - new Model.Version1.ReferencedEntity(2, 3); - - // Generic types - new Sync {Root = helen}; - new Sync {Root = director}; - new Sync {Root = alex}; - - // Commiting changes - transactionScope.Complete(); - } + using (var session = domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { + // BusinessContacts + var helen = new BusinessContact { + Address = new Address { + City = "Cowes", + Country = "UK" + }, + CompanyName = "Island Trading", + ContactName = "Helen Bennett", + PassportNumber = "123" + }; + var philip = new BusinessContact { + Address = new Address { + City = "Brandenburg", + Country = "Germany" + }, + CompanyName = "Koniglich Essen", + ContactName = "Philip Cramer", + PassportNumber = "321" + }; + + // Employies + var director = new Employee { + Address = new Address { + City = "Tacoma", + Country = "USA" + }, + FirstName = "Andrew", + LastName = "Fuller", + HireDate = new DateTime(1992, 8, 13) + }; + var nancy = new Employee { + Address = new Address { + City = "Seattle", + Country = "USA" + }, + FirstName = "Nancy", + LastName = "Davolio", + HireDate = new DateTime(1992, 5, 1), + ReportsTo = director + }; + var michael = new Employee { + Address = new Address { + City = "London", + Country = "UK" + }, + FirstName = "Michael", + LastName = "Suyama", + HireDate = new DateTime(1993, 10, 17), + ReportsTo = director + }; + + // Orders + _ = new Order { + OrderNumber = "1", + Customer = helen, + Employee = michael, + Freight = 12, + OrderDate = new DateTime(1996, 7, 4), + ProductName = "Maxilaku" + }; + _ = new Order { + OrderNumber = "2", + Customer = helen, + Employee = nancy, + Freight = 12, + OrderDate = new DateTime(1996, 7, 4), + ProductName = "Filo Mix" + }; + _ = new Order { + OrderNumber = "3", + Customer = philip, + Employee = michael, + Freight = 12, + OrderDate = new DateTime(1996, 7, 4), + ProductName = "Tourtiere" + }; + _ = new Order { + OrderNumber = "4", + Customer = philip, + Employee = nancy, + Freight = 12, + OrderDate = new DateTime(1996, 7, 4), + ProductName = "Pate chinois" + }; + + // Products & catgories + _ = new Category { + Name = "Web applications", + Products = { new Model.Version1.Product { Name = "HelpServer", IsActive = true } } + }; + + _ = new Category { + Name = "Frameworks", + Products = { new Model.Version1.Product { Name = "DataObjects.NET", IsActive = true } } + }; + + // Boys & girls + var alex = new Model.Version1.Boy("Alex"); + var dmitry = new Model.Version1.Boy("Dmitry"); + var elena = new Model.Version1.Girl("Elena"); + var tanya = new Model.Version1.Girl("Tanya"); + _ = alex.FriendlyGirls.Add(elena); + _ = alex.FriendlyGirls.Add(tanya); + _ = elena.FriendlyBoys.Add(dmitry); + + // EntityX + var e1 = new Model.Version1.Entity1(1); + var e2 = new Model.Version1.Entity2(2, e1); + var e3 = new Model.Version1.Entity3(3, e2); + var e4 = new Model.Version1.Entity4(4, e3); + + // StructureContainerX + var se1 = new Model.Version1.StructureContainer1 { S1 = new Structure1 { E1 = e1 } }; + var se2 = new Model.Version1.StructureContainer2 { S2 = new Structure2 { E2 = e2, S1 = se1.S1 } }; + var se3 = new Model.Version1.StructureContainer3 { S3 = new Structure3 { E3 = e3, S2 = se2.S2 } }; + var se4 = new Model.Version1.StructureContainer4 { S4 = new Structure4 { E4 = e4, S3 = se3.S3 } }; + + // MyStructureOwner, ReferencedEntity + _ = new Model.Version1.MyStructureOwner(0) { Structure = new MyStructure { A = 1, B = 2 } }; + _ = new Model.Version1.MyStructureOwner(1) { Structure = new MyStructure { A = 2, B = 3 } }; + _ = new Model.Version1.ReferencedEntity(1, 2); + _ = new Model.Version1.ReferencedEntity(2, 3); + + // Generic types + _ = new Sync { Root = helen }; + _ = new Sync { Root = director }; + _ = new Sync { Root = alex }; + + // Commiting changes + transactionScope.Complete(); } } From 52f82f011b6e58609e7dfa574a05c4f0b7083789 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 26 Mar 2021 16:23:50 +0500 Subject: [PATCH 37/71] Firebird: Fix tests in Issues group - add requirements to test cases which is not supposed to be run on firebird due to lack of support of ceratain features - workaround for certain test cases to have correct expected results - formatting --- .../Issue0624_EntitySetSubqueryError.cs | 3 +- .../IssueJira0437_OperationsWithListOfInt.cs | 21 ++-- ...ueJira0593_AggregateForSingleColumnTest.cs | 99 +++++++++++-------- ...ira0675_EntityChangeRegistryDoesntClear.cs | 3 +- .../Issues/LocalCollectionsTest.cs | 18 ++-- 5 files changed, 83 insertions(+), 61 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs index 376ecacd8f..ab189164c4 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs @@ -69,7 +69,6 @@ public class Issue0624_EntitySetSubqueryError : AutoBuildTest { protected override void CheckRequirements() { - base.CheckRequirements(); Require.ProviderIsNot(StorageProvider.Oracle | StorageProvider.MySql); } @@ -102,6 +101,8 @@ public void Test01() [Test] public void Test02() { + Require.AnyFeatureSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); + using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { var controlId = Guid.NewGuid(); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0437_OperationsWithListOfInt.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0437_OperationsWithListOfInt.cs index 44aed413cf..5074aa50f9 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0437_OperationsWithListOfInt.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0437_OperationsWithListOfInt.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 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 // Created: 2013.02.22 @@ -35,13 +35,16 @@ protected override DomainConfiguration BuildConfiguration() return configuration; } + protected override void CheckRequirements() + => Require.AnyFeatureSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); + protected override void PopulateData() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - new NamedObject {Name = "One"}; - new NamedObject {Name = "Two"}; - new NamedObject {Name = "Three"}; + _ = new NamedObject {Name = "One"}; + _ = new NamedObject {Name = "Two"}; + _ = new NamedObject {Name = "Three"}; tx.Complete(); } } @@ -49,7 +52,7 @@ protected override void PopulateData() [Test] public void GroupJoinTest() { - Require.AnyFeatureNotSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); + Require.AnyFeatureSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { var items = new List {2, 3}; @@ -66,7 +69,7 @@ into j [Test] public void JoinTest() { - Require.AnyFeatureNotSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); + Require.AnyFeatureSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { var items = new List {1, 2}; @@ -87,7 +90,7 @@ orderby o.Id [Test] public void ApplyTest() { - Require.AnyFeatureNotSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); + Require.AnyFeatureSupported(ProviderFeatures.TemporaryTableEmulation | ProviderFeatures.TemporaryTables); using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { var items = new List {1, 2, 3}; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs index 55deb15439..1a21552cfd 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs @@ -8,6 +8,7 @@ using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Issues.IssueJira0593_AggregateForSingleColumnModel; namespace Xtensive.Orm.Tests.Issues @@ -120,7 +121,7 @@ public class IssueJira0593_AggregateForSingleColumnTest : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.Register(typeof (TestEntity)); + config.Types.Register(typeof(TestEntity)); return config; } @@ -149,7 +150,7 @@ protected override void PopulateData() StringField = "StringField" + i, }; - if (i % 2==0) { + if (i % 2 == 0) { entity.NullableSByteField = entity.SByteField; entity.NullableByteField = entity.ByteField; entity.NullableShortField = entity.ShortField; @@ -176,17 +177,17 @@ public void MainTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var localSum = Query.All().Select(c => c.DecimalField).ToArray().Sum(); - Assert.AreEqual(Query.All().Sum(c => c.DecimalField), localSum); - Assert.AreEqual(Query.All().Select(c => c.DecimalField).Sum(c => c), localSum); - Assert.AreEqual(Query.All().Select(c => c.DecimalField).Sum(), localSum); + var localSum = session.Query.All().Select(c => c.DecimalField).ToArray().Sum(); + Assert.AreEqual(session.Query.All().Sum(c => c.DecimalField), localSum); + Assert.AreEqual(session.Query.All().Select(c => c.DecimalField).Sum(c => c), localSum); + Assert.AreEqual(session.Query.All().Select(c => c.DecimalField).Sum(), localSum); - var query = Query.All().Select(c => c.Name.Contains("3") ? c.DecimalField : -c.DecimalField); + var query = session.Query.All().Select(c => c.Name.Contains("3") ? c.DecimalField : -c.DecimalField); localSum = query.ToArray().Sum(); Assert.AreEqual(query.Sum(c => c), localSum); Assert.AreEqual(query.Sum(), localSum); - var nullableQuery = Query.All().Select(c => c.Name.Contains("3") ? c.NullableDecimalField : -c.NullableDecimalField); + var nullableQuery = session.Query.All().Select(c => c.Name.Contains("3") ? c.NullableDecimalField : -c.NullableDecimalField); var nullableLocalSum = nullableQuery.ToArray().Sum(); Assert.AreEqual(nullableQuery.Sum(c => c), nullableLocalSum); Assert.AreEqual(nullableQuery.Sum(), nullableLocalSum); @@ -198,12 +199,12 @@ public void DifferentColumnsTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains("3") ? c.IntField : -c.ShortField); + var query = session.Query.All().Select(c => c.Name.Contains("3") ? c.IntField : -c.ShortField); var localSum = query.ToArray().Sum(); Assert.AreEqual(query.Sum(c => c), localSum); Assert.AreEqual(query.Sum(), localSum); - var nullableQuery = Query.All().Select(c => c.Name.Contains("3") ? c.DecimalField : -c.NullableDecimalField); + var nullableQuery = session.Query.All().Select(c => c.Name.Contains("3") ? c.DecimalField : -c.NullableDecimalField); var nullableLocalSum = nullableQuery.ToArray().Sum(); Assert.AreEqual(nullableQuery.Sum(c => c), nullableLocalSum); Assert.AreEqual(nullableQuery.Sum(), nullableLocalSum); @@ -217,7 +218,7 @@ public void SByteTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.SByteField : -c.SByteField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.SByteField : -c.SByteField); CheckQueryable(query); } } @@ -227,7 +228,7 @@ public void NullableSByteTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableSByteField : -c.NullableSByteField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableSByteField : -c.NullableSByteField); CheckQueryable(query); } } @@ -237,7 +238,7 @@ public void ByteTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.ByteField : -c.ByteField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.ByteField : -c.ByteField); CheckQueryable(query); } } @@ -247,7 +248,7 @@ public void NullableByteTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableByteField : -c.NullableByteField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableByteField : -c.NullableByteField); CheckQueryable(query); } } @@ -257,7 +258,7 @@ public void ShortTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.ShortField : -c.ShortField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.ShortField : -c.ShortField); CheckQueryable(query); } } @@ -267,7 +268,7 @@ public void NullableShortTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableShortField : -c.NullableShortField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableShortField : -c.NullableShortField); CheckQueryable(query); } } @@ -277,7 +278,7 @@ public void UShortTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.UShortField : -c.UShortField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.UShortField : -c.UShortField); CheckQueryable(query); } } @@ -287,7 +288,7 @@ public void NullableUShortTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableUShortField : -c.NullableUShortField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableUShortField : -c.NullableUShortField); CheckQueryable(query); } } @@ -297,7 +298,7 @@ public void IntTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.IntField : -c.IntField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.IntField : -c.IntField); CheckQueryable(query); } } @@ -307,7 +308,7 @@ public void NullableIntTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableIntField : -c.NullableIntField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableIntField : -c.NullableIntField); CheckQueryable(query); } } @@ -317,7 +318,7 @@ public void UIntTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.UIntField : -c.UIntField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.UIntField : -c.UIntField); CheckQueryable(query); } } @@ -327,7 +328,7 @@ public void NullableUIntTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableUIntField : -c.NullableUIntField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableUIntField : -c.NullableUIntField); CheckQueryable(query); } } @@ -337,7 +338,7 @@ public void LongTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.LongField : -c.LongField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.LongField : -c.LongField); CheckQueryable(query); } } @@ -347,7 +348,7 @@ public void NullableLongTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableLongField : -c.NullableLongField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableLongField : -c.NullableLongField); CheckQueryable(query); } } @@ -357,7 +358,7 @@ public void ULongTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? -(long) c.ULongField : (long) c.ULongField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? -(long) c.ULongField : (long) c.ULongField); CheckQueryable(query); } } @@ -367,7 +368,7 @@ public void NullableULongTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? -(long?) c.NullableULongField : (long?) c.NullableULongField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? -(long?) c.NullableULongField : (long?) c.NullableULongField); CheckQueryable(query); } } @@ -377,7 +378,7 @@ public void FloatTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.FloatField : -c.FloatField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.FloatField : -c.FloatField); CheckQueryable(query); } } @@ -387,7 +388,7 @@ public void NullableFloatTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableFloatField : -c.NullableFloatField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableFloatField : -c.NullableFloatField); CheckQueryable(query); } } @@ -397,7 +398,7 @@ public void DoubleTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.DoubleField : -c.DoubleField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.DoubleField : -c.DoubleField); CheckQueryable(query); } } @@ -407,7 +408,7 @@ public void NullableDoubleTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableDoubleField : -c.NullableDoubleField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableDoubleField : -c.NullableDoubleField); CheckQueryable(query); } } @@ -417,7 +418,7 @@ public void DecimalTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.DecimalField : -c.DecimalField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.DecimalField : -c.DecimalField); CheckQueryable(query); } } @@ -427,7 +428,7 @@ public void NullableDecimalTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableDecimalField : -c.NullableDecimalField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableDecimalField : -c.NullableDecimalField); CheckQueryable(query); } } @@ -441,7 +442,7 @@ public void TimeSpanTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.TimeSpanField : -c.TimeSpanField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.TimeSpanField : -c.TimeSpanField); CheckQueryable(query); } } @@ -451,7 +452,7 @@ public void NullableTimeSpanTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableTimeSpanField : -c.NullableTimeSpanField); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableTimeSpanField : -c.NullableTimeSpanField); CheckQueryable(query); } } @@ -462,7 +463,7 @@ public void DateTimeTest() var now = DateTime.Now; using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.DateTimeField : now); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.DateTimeField : now); CheckQueryable(query); } } @@ -472,7 +473,7 @@ public void NullableDateTimeTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableDateTimeField : null); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableDateTimeField : null); CheckQueryable(query); } } @@ -483,7 +484,7 @@ public void GuidTest() var newGuid = Guid.NewGuid(); using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.GuidField : newGuid); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.GuidField : newGuid); CheckQueryable(query); } } @@ -493,7 +494,7 @@ public void NullableGuidTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableGuidField : null); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.NullableGuidField : null); CheckQueryable(query); } } @@ -503,7 +504,7 @@ public void StringTest() { using (var session = Domain.OpenSession()) using (session.OpenTransaction()) { - var query = Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.StringField : c.Name); + var query = session.Query.All().Select(c => c.Name.Contains(FilterCondition) ? c.StringField : c.Name); CheckQueryable(query); } } @@ -517,8 +518,14 @@ private static void CheckQueryable(IQueryable query) var localArray = query.ToArray(); Assert.AreEqual(localArray.Sum(), query.Sum(c => c)); Assert.AreEqual(localArray.Sum(), query.Sum()); - Assert.AreEqual(localArray.Average(), query.Average(c => c)); - Assert.AreEqual(localArray.Average(), query.Average()); + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird)) { + Assert.AreEqual(Math.Truncate(localArray.Average()), query.Average(c => c)); + Assert.AreEqual(Math.Truncate(localArray.Average()), query.Average()); + } + else { + Assert.AreEqual(localArray.Average(), query.Average(c => c)); + Assert.AreEqual(localArray.Average(), query.Average()); + } Assert.AreEqual(localArray.Min(), query.Min(c => c)); Assert.AreEqual(localArray.Min(), query.Min()); Assert.AreEqual(localArray.Max(), query.Max(c => c)); @@ -545,8 +552,14 @@ private static void CheckQueryable(IQueryable query) var localArray = query.ToArray(); Assert.AreEqual(localArray.Sum(), query.Sum(c => c)); Assert.AreEqual(localArray.Sum(), query.Sum()); - Assert.AreEqual(localArray.Average(), query.Average(c => c)); - Assert.AreEqual(localArray.Average(), query.Average()); + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird)) { + Assert.AreEqual(Math.Truncate(localArray.Average()), query.Average(c => c)); + Assert.AreEqual(Math.Truncate(localArray.Average()), query.Average()); + } + else { + Assert.AreEqual(localArray.Average(), query.Average(c => c)); + Assert.AreEqual(localArray.Average(), query.Average()); + } Assert.AreEqual(localArray.Min(), query.Min(c => c)); Assert.AreEqual(localArray.Min(), query.Min()); Assert.AreEqual(localArray.Max(), query.Max(c => c)); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0675_EntityChangeRegistryDoesntClear.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0675_EntityChangeRegistryDoesntClear.cs index 8f535d438e..0daac39dee 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0675_EntityChangeRegistryDoesntClear.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0675_EntityChangeRegistryDoesntClear.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -74,6 +74,7 @@ public void TestTransactionRollbackOnDeadLock() [Test] public void TestTransactionIsUnsuableAfterDeadlock() { + Require.ProviderIs(StorageProvider.SqlServer); var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => UpdateEntities1(1)); var task2 = System.Threading.Tasks.Task.Factory.StartNew(() => UpdateEntities1(2)); System.Threading.Tasks.Task.WaitAll(task1, task2); diff --git a/Orm/Xtensive.Orm.Tests/Issues/LocalCollectionsTest.cs b/Orm/Xtensive.Orm.Tests/Issues/LocalCollectionsTest.cs index c9c8fbbcdd..a574454355 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/LocalCollectionsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/LocalCollectionsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2011.07.10 @@ -31,7 +31,7 @@ public class LocalCollectionsTest : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.Register(typeof (TextEntity).Assembly, typeof (TextEntity).Namespace); + config.Types.Register(typeof(TextEntity).Assembly, typeof(TextEntity).Namespace); return config; } @@ -41,16 +41,20 @@ public void MainTest() using (var s = Domain.OpenSession()) { using (var t = s.OpenTransaction()) { + var itemCount = StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird) + ? 64000 / 250 //64K limit of Firebird / 250 (which is lenght of field) :) + : 800; + var strings = new HashSet(); - for (int i = 0; i < 800; i++) { - strings.Add(i.ToString()); + for (var i = 0; i < itemCount; i++) { + _ = strings.Add(i.ToString()); } var existing = s.Query.All() .Where(i => i.Text.In(strings)) .Select(i => i.Text); foreach (var text in strings.Except(existing)) { - new TextEntity {Text = text}; + _ = new TextEntity { Text = text }; } t.Complete(); // Rollback From e960e3b5de99e36a6888fc10488f15f01c60d79f Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 26 Mar 2021 16:25:48 +0500 Subject: [PATCH 38/71] Ignore Firebird for test Overflow is unfixable since even decimal max precision is the same as Int64 (18 digits) --- ...thmeticExceptionWhenSubstractionOfDates.cs | 56 ++++++++++--------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0556_ArithmeticExceptionWhenSubstractionOfDates.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0556_ArithmeticExceptionWhenSubstractionOfDates.cs index 374e6f3fbf..6b272011b7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0556_ArithmeticExceptionWhenSubstractionOfDates.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0556_ArithmeticExceptionWhenSubstractionOfDates.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2014 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2014 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2013.09.26 @@ -8,6 +8,7 @@ using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Services; using Xtensive.Orm.Tests.Issues.IssueJira0556_ArithmeticExceptionWhenSubstractionOfDatesModel; namespace Xtensive.Orm.Tests.Issues.IssueJira0556_ArithmeticExceptionWhenSubstractionOfDatesModel @@ -39,34 +40,36 @@ protected override DomainConfiguration BuildConfiguration() return domainConfiguration; } + protected override void CheckRequirements() => Require.ProviderIsNot(StorageProvider.Firebird, "No type that would allow to fix it"); + protected override void PopulateData() { using (var session = Domain.OpenSession()) using (session.Activate()) using (var tx = session.OpenTransaction()) { - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(10)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(100)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(1000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(10000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(100000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(106751)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(120000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(130000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(140000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(150000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(160000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(170000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(180000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(190000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(200000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(300000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(400000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(500000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(600000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(700000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(800000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(900000)}; - new Invoice {CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(1000000)}; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(10) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(100) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(1000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(10000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(100000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(106751) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(120000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(130000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(140000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(150000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(160000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(170000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(180000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(190000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(200000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(300000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(400000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(500000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(600000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(700000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(800000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(900000) }; + _ = new Invoice { CreatedOn = DateTime.MinValue.AddYears(100), InvoicedOn = DateTime.MinValue.AddYears(100).AddDays(1000000) }; tx.Complete(); } } @@ -75,7 +78,6 @@ protected override void PopulateData() public void MainTest() { using (var session = Domain.OpenSession()) - using (session.Activate()) using (var tx = session.OpenTransaction()) { var result = session.Query.All().Where(invoice => (invoice.CreatedOn - invoice.InvoicedOn) > TimeSpan.FromHours(1)).ToList(); } From 4987eefa49c63eccfc910d9f4e22666861e4dc0e Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Mon, 29 Mar 2021 17:36:32 +0500 Subject: [PATCH 39/71] Fix test for some storages - Correct low-level query for Firebird - Right exception to expect for Firebird and Mysql --- ...ailedQueryAndDbCommandNotificationsTest.cs | 69 +++++++++++-------- .../Storage/QueryBuilderTest.cs | 13 +++- 2 files changed, 52 insertions(+), 30 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/FailedQueryAndDbCommandNotificationsTest.cs b/Orm/Xtensive.Orm.Tests/Storage/FailedQueryAndDbCommandNotificationsTest.cs index b414748bbc..ec1488a888 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/FailedQueryAndDbCommandNotificationsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/FailedQueryAndDbCommandNotificationsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Julian Mamokin // Created: 2017.02.08 @@ -38,26 +38,35 @@ public class FailedQueryAndDbCommandNotificationsTest : AutoBuildTest public void InvalidQueryTest() { Exception thrownException = null; - EventHandler invalidQueryHandler = (sender, args) => {thrownException = args.Exception;}; using (var session = Domain.OpenSession()) { - session.Events.QueryExecuted += invalidQueryHandler; - using (session.OpenTransaction()) - Assert.Throws(() => session.Query.All().Single(m => m.SomeStringField=="lol")); - session.Events.QueryExecuted -= invalidQueryHandler; + session.Events.QueryExecuted += InvalidQueryHandler; + using (session.OpenTransaction()) { + _ = Assert.Throws(() => session.Query.All().Single(m => m.SomeStringField == "lol")); + } + session.Events.QueryExecuted -= InvalidQueryHandler; Assert.IsNotNull(thrownException); Assert.AreSame(typeof (InvalidOperationException), thrownException.GetType()); } + + void InvalidQueryHandler(object sender, QueryEventArgs args) + { + thrownException = args.Exception; + } } [Test] public void ValidQueryTest() { - EventHandler validQueryHandler = (sender, args) => { Assert.IsNull(args.Exception); }; using (var session = Domain.OpenSession()) { - session.Events.QueryExecuted += validQueryHandler; + session.Events.QueryExecuted += ValidQueryHandler; using (session.OpenTransaction()) Assert.DoesNotThrow(() => session.Query.All().Single(m => m.SomeStringField=="string1")); - session.Events.QueryExecuted -= validQueryHandler; + session.Events.QueryExecuted -= ValidQueryHandler; + } + + static void ValidQueryHandler(object sender, QueryEventArgs args) + { + Assert.IsNull(args.Exception); } } @@ -65,40 +74,48 @@ public void ValidQueryTest() public void InvalidDbCommandTest() { Exception commandExecutedException = null; - EventHandler invalidDbCommandHandler = (sender, args) => { commandExecutedException = args.Exception; }; using (var session = Domain.OpenSession()) { using (session.OpenTransaction()) { - new TestModel { SomeStringField = "wat", SomeDateTimeField = DateTime.Now, UniqueValue = 1 }; + _ = new TestModel { SomeStringField = "wat", SomeDateTimeField = DateTime.Now, UniqueValue = 1 }; var expectedException = GetUniqueConstraintViolationExceptionType(); - session.Events.DbCommandExecuted += invalidDbCommandHandler; - Assert.Throws(expectedException, () => session.SaveChanges()); - session.Events.DbCommandExecuted -= invalidDbCommandHandler; + session.Events.DbCommandExecuted += InvalidDbCommandHandler; + _ = Assert.Throws(expectedException, () => session.SaveChanges()); + session.Events.DbCommandExecuted -= InvalidDbCommandHandler; Assert.NotNull(commandExecutedException); Assert.AreEqual(expectedException, commandExecutedException.GetType()); } } + + void InvalidDbCommandHandler(object sender, DbCommandEventArgs args) + { + commandExecutedException = args.Exception; + } } [Test] public void ValidDbCommandTest() { - EventHandler validDbCommandHandler = (sender, args) => { Assert.IsNull(args.Exception); }; using (var session = Domain.OpenSession()) { using (session.OpenTransaction()) { - new TestModel { SomeStringField = "wat", SomeDateTimeField = DateTime.Now, UniqueValue = 3 }; - new TestModel { SomeStringField = "dat", SomeDateTimeField = DateTime.Now, UniqueValue = 4 }; - session.Events.DbCommandExecuted += validDbCommandHandler; + _ = new TestModel { SomeStringField = "wat", SomeDateTimeField = DateTime.Now, UniqueValue = 3 }; + _ = new TestModel { SomeStringField = "dat", SomeDateTimeField = DateTime.Now, UniqueValue = 4 }; + session.Events.DbCommandExecuted += ValidDbCommandHandler; Assert.DoesNotThrow(() => session.SaveChanges()); - session.Events.DbCommandExecuted -= validDbCommandHandler; + session.Events.DbCommandExecuted -= ValidDbCommandHandler; } } + + static void ValidDbCommandHandler(object sender, DbCommandEventArgs args) + { + Assert.IsNull(args.Exception); + } } protected override void PopulateData() { using(var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestModel { SomeStringField = "string1", SomeDateTimeField = DateTime.Now, UniqueValue = 1 }; + _ = new TestModel { SomeStringField = "string1", SomeDateTimeField = DateTime.Now, UniqueValue = 1 }; transaction.Complete(); } } @@ -106,7 +123,7 @@ protected override void PopulateData() protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (TestModel).Assembly, typeof (TestModel).Namespace); + configuration.Types.Register(typeof(TestModel).Assembly, typeof(TestModel).Namespace); configuration.UpgradeMode = DomainUpgradeMode.Recreate; return configuration; } @@ -115,12 +132,10 @@ private Type GetUniqueConstraintViolationExceptionType() { var providerName = ProviderInfo.ProviderName; switch (providerName) { - case WellKnown.Provider.MySql: case WellKnown.Provider.Sqlite: - case WellKnown.Provider.Firebird: - return typeof (StorageException); + return typeof(StorageException); default: - return typeof (UniqueConstraintViolationException); + return typeof(UniqueConstraintViolationException); } } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/QueryBuilderTest.cs b/Orm/Xtensive.Orm.Tests/Storage/QueryBuilderTest.cs index 08a91578cf..edc4de3899 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/QueryBuilderTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/QueryBuilderTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012-2020 Xtensive LLC. +// Copyright (C) 2012-2021 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 @@ -37,7 +37,7 @@ protected override void PopulateData() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - new CheckEntity(); + _ = new CheckEntity(); tx.Complete(); } } @@ -86,7 +86,14 @@ public void ComposeQuery() Assert.That(builder, Is.Not.Null); var binding = builder.CreateParameterBinding(typeof(int), () => 43); - var select = SqlDml.Select(binding.ParameterReference); + SqlSelect select; + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird)) { + //require cast of parameters on sql level + select = SqlDml.Select(SqlDml.Cast(binding.ParameterReference, SqlType.Int32)); + } + else { + select = SqlDml.Select(binding.ParameterReference); + } var compiled = builder.CompileQuery(select); Assert.That(compiled, Is.Not.Null); From 09ec31188ab1364b6f4c61f64ab52322dc4770fc Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 30 Mar 2021 13:14:58 +0500 Subject: [PATCH 40/71] Firebird: wierd reader behavior workaround - regular tests ignored for Firebird - added special tests for Firebird --- .../PersistWithAsyncQueriesTest.cs | 382 +++++++++++++----- 1 file changed, 276 insertions(+), 106 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs index 70e5371bf9..37d6341b68 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs @@ -1,14 +1,16 @@ -// Copyright (C) 2019 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2019-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2019.07.12 using System; +using System.Linq; using System.Threading.Tasks; using NUnit.Framework; using Xtensive.Core; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Storage.AsyncQueries.PersistWithAsyncQueriesTestModel; namespace Xtensive.Orm.Tests.Storage.AsyncQueries.PersistWithAsyncQueriesTestModel @@ -59,7 +61,7 @@ public class PersistWithAsyncQueriesTest : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (TestEntity).Assembly, typeof (TestEntity).Namespace); + configuration.Types.Register(typeof(TestEntity).Assembly, typeof(TestEntity).Namespace); configuration.UpgradeMode = DomainUpgradeMode.Recreate; return configuration; } @@ -68,35 +70,38 @@ protected override void PopulateData() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - for (int i = 0; i < TestEntityCount; i++) - new TestEntity(session) {Value = i}; + for (var i = 0; i < TestEntityCount; i++) { + _ = new TestEntity(session) { Value = i }; + } + transaction.Complete(); } } [Test] - public async Task AsyncButFullySequential() + public async Task AsyncButFullySequentialTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = await session.Query.All().AsAsync(); var anotherAsyncQuery = await session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in readyToRockQuery) + var count = 0; + foreach (var testEntity in readyToRockQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount)); count = 0; - foreach (var testEntity in anotherAsyncQuery) + foreach (var testEntity in anotherAsyncQuery) { count++; - + } Assert.That(count, Is.EqualTo(TestEntityCount)); } } [Test] - public async Task QueryFirstWaitLater() + public async Task QueryFirstWaitLaterTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { @@ -106,36 +111,38 @@ public async Task QueryFirstWaitLater() // some local non-DO work probably; - int count = 0; - foreach (var testEntity in await readyToRockQuery) + var count = 0; + foreach (var testEntity in await readyToRockQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount)); count = 0; - foreach (var testEntity in await anotherAsyncQuery) + foreach (var testEntity in await anotherAsyncQuery) { count++; - + } Assert.That(count, Is.EqualTo(TestEntityCount)); } } [Test] - public async Task QueryFirstWaitLaterInDiffferentOrder() + public async Task QueryFirstWaitLaterInDiffferentOrderTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()){ var readyToRockQuery = session.Query.All().AsAsync(); var anotherAsyncQuery = session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in await anotherAsyncQuery) + var count = 0; + foreach (var testEntity in await anotherAsyncQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount)); count = 0; - foreach (var testEntity in await readyToRockQuery) + foreach (var testEntity in await readyToRockQuery) { count++; - + } Assert.That(count, Is.EqualTo(TestEntityCount)); } } @@ -143,29 +150,65 @@ public async Task QueryFirstWaitLaterInDiffferentOrder() [Test] public async Task ProperPersistSequenceTest() { + Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var readyToRockQuery = await session.Query.All().AsAsync(); - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var anotherAsyncQuery = await session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in readyToRockQuery) + var count = 0; + foreach (var testEntity in readyToRockQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); count = 0; - foreach (var testEntity in anotherAsyncQuery) + foreach (var testEntity in anotherAsyncQuery) { count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount + 6)); + } + } + + [Test] + public async Task ProperPersistSequenceFirebirdTest() + { + Require.ProviderIs(StorageProvider.Firebird); + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + var readyToRockQuery = await session.Query.All().AsAsync(); + + var count = 0; + foreach (var testEntity in readyToRockQuery) { + count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount + 3)); + + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + + var anotherAsyncQuery = await session.Query.All().AsAsync(); + + count = 0; + foreach (var testEntity in anotherAsyncQuery) { + count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 6)); } } @@ -175,23 +218,24 @@ public async Task PersistBeforeFirstAsyncQueryAwaitTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var readyToRockQuery = await session.Query.All().AsAsync(); var anotherAsyncQuery = await session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in readyToRockQuery) + var count = 0; + foreach (var testEntity in readyToRockQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); count = 0; - foreach (var testEntity in anotherAsyncQuery) + foreach (var testEntity in anotherAsyncQuery) { count++; - + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); } } @@ -199,25 +243,55 @@ public async Task PersistBeforeFirstAsyncQueryAwaitTest() [Test] public async Task PersistBeforeSecondAsyncQueryAwaitTest() { + Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = await session.Query.All().AsAsync(); - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var anotherAsyncQuery = await session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in readyToRockQuery) + var count = 0; + foreach (var testEntity in readyToRockQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount)); count = 0; - foreach (var testEntity in anotherAsyncQuery) + foreach (var testEntity in anotherAsyncQuery) { + count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount + 3)); + } + } + + [Test] + public async Task PersistBeforeSecondAsyncQueryAwaitFirebirdTest() + { + Require.ProviderIs(StorageProvider.Firebird); + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var readyToRockQuery = await session.Query.All().AsAsync(); + + var count = 0; + foreach (var testEntity in readyToRockQuery) { count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount)); + + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + + var anotherAsyncQuery = await session.Query.All().AsAsync(); + count = 0; + foreach (var testEntity in anotherAsyncQuery) { + count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); } } @@ -225,53 +299,89 @@ public async Task PersistBeforeSecondAsyncQueryAwaitTest() [Test] public async Task PersistBeforeBothAsyncQueriesAndDelayedWaitTest() { + Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestEntity(session) {Value = 101}; - new TestEntity(session) {Value = 102}; - new TestEntity(session) {Value = 103}; + _ = new TestEntity(session) { Value = 101 }; + _ = new TestEntity(session) { Value = 102 }; + _ = new TestEntity(session) { Value = 103 }; var readyToRockQuery = session.Query.All().AsAsync(); - new TestEntity(session) { Value = 104 }; - new TestEntity(session) { Value = 105 }; - new TestEntity(session) { Value = 106 }; + _ = new TestEntity(session) { Value = 104 }; + _ = new TestEntity(session) { Value = 105 }; + _ = new TestEntity(session) { Value = 106 }; var anotherAsyncQuery = session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in await anotherAsyncQuery) + var count = 0; + foreach (var testEntity in await anotherAsyncQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 6)); count = 0; - foreach (var testEntity in await readyToRockQuery) + foreach (var testEntity in await readyToRockQuery) { count++; - + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); } } + [Test] + public async Task PersistBeforeBothAsyncQueriesAndDelayedWaitFirebirdTest() + { + Require.ProviderIs(StorageProvider.Firebird); + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new TestEntity(session) { Value = 101 }; + _ = new TestEntity(session) { Value = 102 }; + _ = new TestEntity(session) { Value = 103 }; + + var readyToRockQuery = session.Query.All().AsAsync(); + + _ = new TestEntity(session) { Value = 104 }; + _ = new TestEntity(session) { Value = 105 }; + _ = new TestEntity(session) { Value = 106 }; + + var anotherAsyncQuery = session.Query.All().AsAsync(); + + var count = 0; + foreach (var testEntity in await anotherAsyncQuery) { + count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount + 6)); + + count = 0; + foreach (var testEntity in await readyToRockQuery) { + count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount + 6)); + } + } + [Test] public async Task PersistBeforeFirstAsyncQueryAndDalayedAwaitTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var readyToRockQuery = session.Query.All().AsAsync(); var anotherAsyncQuery = session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in await anotherAsyncQuery) + var count = 0; + foreach (var testEntity in await anotherAsyncQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); count = 0; - foreach (var testEntity in await readyToRockQuery) + foreach (var testEntity in await readyToRockQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); } @@ -280,128 +390,189 @@ public async Task PersistBeforeFirstAsyncQueryAndDalayedAwaitTest() [Test] public async Task PersistBeforeSecondAsyncQueryAndDelayedAwaitTest() { + Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = session.Query.All().AsAsync(); - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var anotherAsyncQuery = session.Query.All().AsAsync(); - int count = 0; - foreach (var testEntity in await anotherAsyncQuery) + var count = 0; + foreach (var testEntity in await anotherAsyncQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); count = 0; - foreach (var testEntity in await readyToRockQuery) + foreach (var testEntity in await readyToRockQuery) { count++; - + } Assert.That(count, Is.EqualTo(TestEntityCount)); } } + [Test] + public async Task PersistBeforeSecondAsyncQueryAndDelayedAwaitFirebirdTest() + { + Require.ProviderIs(StorageProvider.Firebird); + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var readyToRockQuery = session.Query.All().AsAsync(); + + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + + var anotherAsyncQuery = session.Query.All().AsAsync(); + + var count = 0; + foreach (var testEntity in await anotherAsyncQuery) { + count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount + 3)); + + count = 0; + foreach (var testEntity in await readyToRockQuery) { + count++; + } + Assert.That(count, Is.EqualTo(TestEntityCount + 3)); + } + } + #region Manual persist [Test] - public async Task ProperManualSavingChanges() + public async Task ProperManualSavingChangesTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var count = 0; - foreach (var entity in await session.Query.All().AsAsync()) + foreach (var entity in await session.Query.All().AsAsync()) { count++; + } - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); session.SaveChanges(); Assert.That(count, Is.EqualTo(TestEntityCount + 3)); - count = 0; - session.Query.All().ForEach((e) => count++); + count = session.Query.All().AsEnumerable().Count(); Assert.That(count, Is.EqualTo(TestEntityCount + 6)); } } [Test] - public async Task AwaitingQueryBeforeManualSavingChanges() + public async Task AwaitingQueryBeforeManualSavingChangesTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var readyToRockQuery = session.Query.All().AsAsync(); - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); - int count = 0; - foreach (var entity in await readyToRockQuery) + var count = 0; + foreach (var entity in await readyToRockQuery) { count++; + } session.SaveChanges(); Assert.That(count, Is.EqualTo(TestEntityCount + 3)); - count = 0; - session.Query.All().ForEach((e) => count++); + count = session.Query.All().AsEnumerable().Count(); Assert.That(count, Is.EqualTo(TestEntityCount + 6)); } } [Test] - public async Task ManualSavingDuringAsyncQueryExecution() + public async Task ManualSavingDuringAsyncQueryExecutionTest() { + Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); var readyToRockQuery = session.Query.All().AsAsync(); - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); session.SaveChanges(); - int count = 0; - foreach (var entity in await readyToRockQuery) + var count = 0; + foreach (var entity in await readyToRockQuery) { count++; + } Assert.That(count, Is.EqualTo(TestEntityCount + 3)); - count = 0; - session.Query.All().ForEach((e)=> count++); + count = session.Query.All().AsEnumerable().Count(); + Assert.That(count, Is.EqualTo(TestEntityCount + 6)); + } + } + + [Test] + public async Task ManualSavingDuringAsyncQueryExecutionFirebirdTest() + { + Require.ProviderIs(StorageProvider.Firebird); + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + + var readyToRockQuery = session.Query.All().AsAsync(); + + var count = 0; + foreach (var entity in await readyToRockQuery) { + count++; + } + + Assert.That(count, Is.EqualTo(TestEntityCount + 3)); + + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + + session.SaveChanges(); + + count = session.Query.All().AsEnumerable().Count(); Assert.That(count, Is.EqualTo(TestEntityCount + 6)); } } [Test] - public async Task ManualSavingDuringEnumeration() + public async Task ManualSavingDuringEnumerationTest() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = session.Query.All().AsAsync(); - new TestEntity(session); - new TestEntity(session); - new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); + _ = new TestEntity(session); - bool shouldPersist = true; + var shouldPersist = true; - int count = 0; + var count = 0; foreach (var entity in await readyToRockQuery) { if (count > 10 && shouldPersist) { session.SaveChanges(); @@ -411,8 +582,7 @@ public async Task ManualSavingDuringEnumeration() } Assert.That(count, Is.EqualTo(TestEntityCount)); - count = 0; - session.Query.All().ForEach((e) => count++); + count = session.Query.All().AsEnumerable().Count(); Assert.That(count, Is.EqualTo(TestEntityCount + 3)); } } From e844c9988b54c714e4dadbd1ae99e20aaefc6df7 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 30 Mar 2021 19:20:44 +0500 Subject: [PATCH 41/71] More tests fixed for Firebird --- Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs | 43 ++++++++++++++++++--- Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs | 20 +++++----- Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs | 17 +++++++- 3 files changed, 65 insertions(+), 15 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs index b9b29dfe7b..3538691750 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs @@ -1,9 +1,10 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.02.04 +using System; using System.Linq; using NUnit.Framework; using Xtensive.Orm.Providers; @@ -38,7 +39,22 @@ public void OrderBy2Test() .Select(c => c.Address.City) .Distinct() .OrderBy(c => c); - Assert.IsTrue(expected.SequenceEqual(result)); + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird | StorageProvider.Sqlite)) { + var storage = result.AsEnumerable().Where(c => !c.StartsWith('S')); + var local = expected.Where(c => !c.StartsWith('S')); + Assert.IsTrue(local.SequenceEqual(storage)); + var storageHashset = result.AsEnumerable().Where(c => c.StartsWith('S')).ToHashSet(); + local = expected.Where(c => c.StartsWith('S')); + var count = 0; + foreach (var item in local) { + Assert.That(storageHashset.Contains(item)); + count++; + } + Assert.That(storageHashset.Count, Is.EqualTo(count)); + } + else { + Assert.IsTrue(expected.SequenceEqual(result)); + } QueryDumper.Dump(result); } @@ -95,7 +111,23 @@ public void DistinctOrderByTest() .Select(c => c.Address.City) .Distinct() .OrderBy(c => c); - Assert.IsTrue(expected.SequenceEqual(result)); + + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird | StorageProvider.Sqlite)) { + var storage = result.AsEnumerable().Where(c => !c.StartsWith('S')); + var local = expected.Where(c => !c.StartsWith('S')); + Assert.IsTrue(local.SequenceEqual(storage)); + var storageHashset = result.AsEnumerable().Where(c => c.StartsWith('S')).ToHashSet(); + local = expected.Where(c => c.StartsWith('S')); + var count = 0; + foreach (var item in local) { + Assert.That(storageHashset.Contains(item)); + count++; + } + Assert.That(storageHashset.Count, Is.EqualTo(count)); + } + else { + Assert.IsTrue(expected.SequenceEqual(result)); + } QueryDumper.Dump(result); } @@ -316,6 +348,7 @@ public void DistinctSkipTest() .Distinct() .OrderBy(c => c.LastName) .Skip(5); + Assert.IsTrue(expected.SequenceEqual(result)); Assert.Greater(result.ToList().Count, 0); } diff --git a/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs b/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs index 64c5a8c2f1..8af862be42 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs @@ -1,9 +1,10 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2009.01.29 +using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; @@ -85,11 +86,11 @@ public void OrderByAnonymous2Test() { IQueryable customers = Session.Query.All(); var result = customers - .Select(c => new {c.Address.Country, c}) + .Select(c => new {c.SupportRep.EmployeeId, c}) .OrderBy(x => x); - var expected = customers.ToList() - .Select(c => new {c.Address.Country, c}) - .OrderBy(x => x.Country) + var expected = Customers + .Select(c => new {c.SupportRep.EmployeeId, c}) + .OrderBy(x => x.EmployeeId) .ThenBy(x => x.c.CustomerId); Assert.That(result, Is.Not.Empty); Assert.IsTrue(expected.SequenceEqual(result)); @@ -308,10 +309,11 @@ public void SelectTest() [Test] public void ThenByTest() { - var result = Session.Query.All().OrderBy(c => c.Address.Country) + var result = Session.Query.All().OrderBy(c => c.SupportRep.EmployeeId) .ThenBy(c => c.Phone).Select(c => c.Address.City); - var expected = Customers.OrderBy(c => c.Address.Country) + var expected = Customers.OrderBy(c => c.SupportRep.EmployeeId) .ThenBy(c => c.Phone).Select(c => c.Address.City); + Assert.That(result, Is.Not.Empty); Assert.IsTrue(expected.SequenceEqual(result)); } diff --git a/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs b/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs index 61c956124e..abacf2e574 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs @@ -539,13 +539,28 @@ from t in tracks [Test] public void NestedQueryTest() { + Require.ProviderIsNot(StorageProvider.Firebird); var tracks = Session.Query.All(); var result = from pd in from t in tracks select new { ProductKey = t.Key, t.Name, TotalPrice = t.UnitPrice * t.UnitPrice } - where pd.TotalPrice > 100 + where pd.TotalPrice > 3.96005m select new { PKey = pd.ProductKey, pd.Name, Total = pd.TotalPrice }; + var list = result.ToList(213); + } + + [Test] + public void NestedQueryFirebirdTest() + { + Require.ProviderIs(StorageProvider.Firebird); + var tracks = Session.Query.All(); + var result = from pd in + from t in tracks + select new { ProductKey = t.Key, t.Name, TotalPrice = t.UnitPrice + t.UnitPrice } + where pd.TotalPrice > 3 + select new { PKey = pd.ProductKey, pd.Name, Total = pd.TotalPrice }; + var list = result.ToList(); } From db675edee9ae5c6802e946a78ffc28237146fad4 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 1 Apr 2021 13:44:31 +0500 Subject: [PATCH 42/71] Less items for groupby over expression Some storages are really slow in such queries --- Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs b/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs index f72136b121..10e2de18ec 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs @@ -531,7 +531,8 @@ public void GroupBySelectKeyTest() [Test] public void GroupBySelectKeyWithSelectCalculableColumnTest() { - IQueryable result = Session.Query.All().GroupBy(t => t.Name).Select(g => g.Key + "String"); + //avoid great amout of data for grouping, some storages are painfully slow with such operation + var result = Session.Query.All().GroupBy(t => t.LastName).Select(g => g.Key + "String"); Assert.That(result, Is.Not.Empty); QueryDumper.Dump(result); } @@ -539,7 +540,8 @@ public void GroupBySelectKeyWithSelectCalculableColumnTest() [Test] public void GroupBySelectKeyWithCalculableColumnTest() { - var result = Session.Query.All().GroupBy(t => t.Name + "String"); + //avoid great amout of data for grouping, some storages are painfully slow with such operation + var result = Session.Query.All().GroupBy(t => t.LastName + "String"); var list = result.ToList(); Assert.That(result, Is.Not.Empty); DumpGrouping(result); From 910f12c5b23eb3467b89ca8124d721df3d8220ca Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 31 Mar 2021 19:34:52 +0500 Subject: [PATCH 43/71] Chinook-based tests: Use cached enumerables instead of query + enumeration --- Orm/Xtensive.Orm.Tests/Linq/AggregateTest.cs | 10 +-- Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs | 24 +++---- Orm/Xtensive.Orm.Tests/Linq/ComplexTest.cs | 19 +++--- Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs | 62 +++++++------------ Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs | 16 +++-- Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs | 8 +-- Orm/Xtensive.Orm.Tests/Linq/InTest.cs | 42 ++++++------- .../Linq/IndexedMethodsTest.cs | 16 +++-- .../Linq/Interfaces/SimpleTest.cs | 10 +-- Orm/Xtensive.Orm.Tests/Linq/JoinTest.cs | 26 ++++---- .../Linq/LocalCollectionsTest.cs | 50 +++++++-------- Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs | 19 +++--- .../Linq/QueryMethodTests.cs | 33 ++++------ Orm/Xtensive.Orm.Tests/Linq/SelectManyTest.cs | 46 +++++++------- Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs | 39 ++++-------- .../Linq/SetOperationsTest.cs | 8 +-- Orm/Xtensive.Orm.Tests/Linq/WhereTest.cs | 33 ++++------ Orm/Xtensive.Orm.Tests/Storage/ApplyTest.cs | 8 +-- .../Storage/CompiledQueryTest.cs | 8 +-- 19 files changed, 202 insertions(+), 275 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/AggregateTest.cs b/Orm/Xtensive.Orm.Tests/Linq/AggregateTest.cs index f98bc4f4c2..da0c85d497 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/AggregateTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/AggregateTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.02.04 @@ -101,7 +101,7 @@ public void CountWithNoPredicateTest() public void CountWithPredicateTest() { var count = Session.Query.All().Count(o => o.InvoiceId > 10); - var expected = Session.Query.All().ToList().Count(o => o.InvoiceId > 10); + var expected = Invoices.Count(o => o.InvoiceId > 10); Assert.AreEqual(expected, count); Assert.Greater(count, 0); } @@ -282,7 +282,7 @@ public void SelectMaxTest() public void SumCountTest() { Require.ProviderIsNot(StorageProvider.SqlServerCe | StorageProvider.Oracle); - var expected = Session.Query.All().ToList().Count(); + var expected = Invoices.Count(); var count = Session.Query.All() .Sum(c => Session.Query.All().Count(o => o.Customer==c)); Assert.AreEqual(expected, count); diff --git a/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs b/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs index c1cb6d7abd..12d4adbd59 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2009.04.30 @@ -37,7 +37,7 @@ public void NewIntArrayTest() public void NewByteArrayTest() { var result = Session.Query.All().Select(x => new byte[] {1, 2}); - var expected = Session.Query.All().ToList().Select(x => new byte[] {1, 2}); + var expected = Customers.Select(x => new byte[] {1, 2}); var comparer = AdvancedComparer.Default.EqualityComparerImplementation; Assert.AreEqual(0, expected.Except(result, comparer).Count()); QueryDumper.Dump(result); @@ -51,7 +51,7 @@ public void NewStringArrayTest() customer.CompanyName, customer.LastName }); - var expected = Session.Query.All() + var expected = Customers .ToList() .Select(customer => new[] { customer.CompanyName, @@ -71,8 +71,7 @@ public void NewByteArrayAnonymousTest() Value = new byte[] {1, 2, 3}, p.Name }); - var expected = Session.Query.All() - .ToList() + var expected = Tracks .Select(p => new { Value = new byte[] {1, 2, 3}, p.Name @@ -107,7 +106,7 @@ orderby r.Name Assert.AreEqual(method, i.Method); var expected = from r in - from p in Session.Query.All().ToList() + from p in Tracks select new { Value = new byte[] {1, 2, 3}, Method = method, @@ -137,8 +136,7 @@ public void ArrayMemberAccessTest() customer.LastName }) .Select(a => a[0]); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(customer => new[] { customer.CompanyName, customer.LastName @@ -156,8 +154,7 @@ public void ArrayAggregateAccessTest() .Select(x => new byte[] {1, 2}) .Select(a => a[0]) .Sum(b => b); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(x => new byte[] {1, 2}) .Select(a => a[0]) .Sum(b => b); @@ -172,8 +169,7 @@ public void ArrayExpressionIndexAccessTest() var bytes = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; var result = Session.Query.All() .Select(e => bytes[e.EmployeeId]); - var expected = Session.Query.All() - .ToList() + var expected = Employees .Select(e => bytes[e.EmployeeId]); Assert.AreEqual(0, expected.Except(result).Count()); QueryDumper.Dump(result); diff --git a/Orm/Xtensive.Orm.Tests/Linq/ComplexTest.cs b/Orm/Xtensive.Orm.Tests/Linq/ComplexTest.cs index 08086a123b..ffa77abe98 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/ComplexTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/ComplexTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.02.25 @@ -107,10 +107,8 @@ public void SubqueryCalculableColumnTest() .Select(invoice => Session.Query.All() .Where(p=>p.Invoice==invoice) .Count()); - var expectedResult = Session.Query.All() - .ToList() - .Select(invoice => Session.Query.All() - .ToList() + var expectedResult = Invoices + .Select(invoice => InvoiceLines .Where(p=>p.Invoice==invoice) .Count()); Assert.AreEqual(0, expectedResult.Except(result).Count()); @@ -145,8 +143,8 @@ from c in Session.Query.All() orderby Session.Query.All().Where(o => o.Customer==c).Count() , c.CustomerId select c; var expected = - from c in Session.Query.All().ToList() - orderby Session.Query.All().ToList().Where(o => o.Customer==c).Count() , c.CustomerId + from c in Customers + orderby Invoices.Where(o => o.Customer==c).Count() , c.CustomerId select c; var resultList = result.ToList(); var expectedList = expected.ToList(); @@ -178,8 +176,7 @@ public void GroupByWithSelectorSelectManyTest() .GroupBy(c => c.Track.Name, (trackName, invoiceLines) => invoiceLines.Where(k => k.Invoice.Customer.FirstName.Substring(0, 1)==trackName.Substring(0, 1))) .SelectMany(k => k); - var expected = Session.Query.All() - .ToList() + var expected = InvoiceLines .GroupBy(c => c.Track.Name, (trackName, invoiceLines) => invoiceLines.Where(k => k.Invoice.Customer.FirstName.Substring(0, 1)==trackName.Substring(0, 1))) .SelectMany(k => k); diff --git a/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs index 3538691750..3fecdb2623 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs @@ -33,8 +33,7 @@ public void OrderBy2Test() .Select(c => c.Address.City) .Distinct() .OrderBy(c => c); - var expected = Session.Query.All() - .ToList() + var expected = Customers .OrderBy(c => c.CompanyName) .Select(c => c.Address.City) .Distinct() @@ -62,7 +61,7 @@ public void OrderBy2Test() public void DefaultTest() { var result = Session.Query.All().Distinct(); - var expected = Session.Query.All().ToList().Distinct(); + var expected = Customers.Distinct(); Assert.AreEqual(0, expected.Except(result).Count()); Assert.Greater(result.ToList().Count, 0); } @@ -73,8 +72,7 @@ public void ScalarTest() var result = Session.Query.All() .Select(c => c.Address.City) .Distinct(); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => c.Address.City) .Distinct(); Assert.AreEqual(0, expected.Except(result).Count()); @@ -89,8 +87,7 @@ public void OrderByTest() .Select(c => c.Address.City) .Distinct() .ToList(); - var expected = Session.Query.All() - .ToList() + var expected = Customers .OrderBy(c => c.CustomerId) .Select(c => c.Address.City) .Distinct(); @@ -106,8 +103,7 @@ public void DistinctOrderByTest() .Select(c => c.Address.City) .Distinct() .OrderBy(c => c); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => c.Address.City) .Distinct() .OrderBy(c => c); @@ -137,8 +133,7 @@ public void CountTest() var result = Session.Query.All() .Distinct() .Count(); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Distinct() .Count(); Assert.AreEqual(expected, result); @@ -151,8 +146,7 @@ public void SelectDistinctCountTest() .Select(c => c.Address.City) .Distinct() .Count(); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => c.Address.City) .Distinct() .Count(); @@ -168,8 +162,7 @@ public void NestedSelectDistinctCountTest() .Select(a => a.City) .Distinct() .Count(); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => c.Address) .Select(a => a.City) .Distinct() @@ -184,8 +177,7 @@ public void CountPredicateTest() var result = Session.Query.All() .Distinct() .Count(c => c.FirstName=="Leonie"); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Distinct() .Count(c => c.FirstName=="Leonie"); Assert.AreEqual(expected, result); @@ -198,8 +190,7 @@ public void SumWithArgTest() var result = Session.Query.All() .Distinct() .Sum(o => o.InvoiceId); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .Distinct() .Sum(o => o.InvoiceId); Assert.AreEqual(expected, result); @@ -213,8 +204,7 @@ public void SumTest() .Select(o => o.InvoiceId) .Distinct() .Sum(); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .Select(o => o.InvoiceId) .Distinct() .Sum(); @@ -232,8 +222,7 @@ public void TakeTest() .Distinct() .OrderBy(o => o.InvoiceId) .ToList(); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .OrderBy(o => o.InvoiceId) .Take(5) .Distinct() @@ -249,8 +238,7 @@ public void TakeTakeTest() .OrderBy(o => o.InvoiceId) .Take(2) .Take(1); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .OrderBy(o => o.InvoiceId) .Take(2) .Take(1); @@ -275,8 +263,7 @@ public void DistinctTakeTest() .Distinct() .OrderBy(o => o.InvoiceId) .Take(5); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .Distinct() .OrderBy(o => o.InvoiceId) .Take(5); @@ -291,8 +278,7 @@ public void TakeCountTest() .Distinct() .Take(5) .Count(); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .Distinct() .Take(5) .Count(); @@ -307,8 +293,7 @@ public void TakeDistinctCountTest() .Take(5) .Distinct() .Count(); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .Take(5) .Distinct() .Count(); @@ -325,8 +310,7 @@ public void SkipTest() .Skip(5) .Select(o => o.InvoiceDate) .Distinct().OrderBy(d => d); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .OrderBy(o => o.InvoiceDate) .Skip(5) .Select(o => o.InvoiceDate) @@ -343,8 +327,7 @@ public void DistinctSkipTest() .Distinct() .OrderBy(c => c.LastName) .Skip(5); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Distinct() .OrderBy(c => c.LastName) .Skip(5); @@ -364,8 +347,7 @@ public void SkipTakeTest() .Select(o => o.InvoiceDate) .Distinct() .OrderBy(d => d); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .OrderBy(o => o.InvoiceDate) .Skip(5) .Take(10) @@ -387,8 +369,7 @@ public void TakeSkipTest() .Select(o => o.InvoiceDate) .Distinct() .OrderBy(d => d); - var expected = Session.Query.All() - .ToList() + var expected = Invoices .OrderBy(o => o.InvoiceDate) .Take(10) .Skip(5) @@ -409,8 +390,7 @@ public void DistinctSkipTakeTest() .OrderBy(c => c) .Skip(5) .Take(10); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => c.FirstName) .Distinct() .OrderBy(c => c) diff --git a/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs b/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs index 928642f3a6..99e4a5c39c 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/EntitySetTest.cs @@ -23,8 +23,7 @@ public void EntitySetAnonymousTest() { var result = Session.Query.All() .Select(c => new { InvoicesFiled = c.Invoices }); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => new { InvoicesFiled = c.Invoices }); Assert.AreEqual(0, expected.Except(result).Count()); QueryDumper.Dump(result); @@ -36,8 +35,7 @@ public void EntitySetSelectManyAnonymousTest() var result = Session.Query.All() .Select(c => new { InvoicesFiled = c.Invoices }) .SelectMany(i => i.InvoicesFiled); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => new { InvoicesFiled = c.Invoices }) .SelectMany(i => i.InvoicesFiled); Assert.AreEqual(0, expected.Except(result).Count()); @@ -48,7 +46,7 @@ public void EntitySetSelectManyAnonymousTest() public void EntitySetSelectTest() { var result = Session.Query.All().OrderBy(c=>c.CustomerId).Select(c => c.Invoices).ToList(); - var expected = Session.Query.All().AsEnumerable().OrderBy(c=>c.CustomerId).Select(c => c.Invoices).ToList(); + var expected = Customers.OrderBy(c=>c.CustomerId).Select(c => c.Invoices).ToList(); Assert.Greater(result.Count, 0); Assert.AreEqual(expected.Count, result.Count); for (var i = 0; i < result.Count; i++) { @@ -62,7 +60,7 @@ public void QueryTest() var customer = GetCustomer(); var expected = customer .Invoices - .ToList() + .AsEnumerable() .OrderBy(i => i.InvoiceId) .Select(i => i.InvoiceId) .ToList(); @@ -85,7 +83,7 @@ public void UnsupportedMethodsTest() public void CountTest() { Require.ProviderIsNot(StorageProvider.SqlServerCe | StorageProvider.Oracle); - var expected = Session.Query.All().Count(); + var expected = Invoices.Count(); var count = Session.Query.All() .Select(c => c.Invoices.Count) .ToList() @@ -123,9 +121,9 @@ join e in Session.Query.All() on i.DesignatedEmployee equals e Assert.AreEqual(customer.Invoices.Count, result.ToList().Count); } - private static Customer GetCustomer() + private Customer GetCustomer() { - return Session.Demand().Query.All().Where(c => c.FirstName == "Aaron").Single(); + return Session.Query.All().Where(c => c.FirstName == "Aaron").Single(); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs b/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs index 10e2de18ec..03fd013f9a 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/GroupByTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.02.04 @@ -110,7 +110,7 @@ public void EntityGroupWithOrderTest() { var result = Session.Query.All().GroupBy(t =>t).OrderBy(g => g.Key.TrackId); var resultList = result.ToList(); - var expectedList = Session.Query.All().ToList().GroupBy(t => t).OrderBy(g => g.Key.TrackId).ToList(); + var expectedList = Tracks.GroupBy(t => t).OrderBy(g => g.Key.TrackId).ToList(); Assert.That(resultList, Is.Not.Empty); Assert.AreEqual(resultList.Count, expectedList.Count()); for (var i = 0; i < resultList.Count; i++) { diff --git a/Orm/Xtensive.Orm.Tests/Linq/InTest.cs b/Orm/Xtensive.Orm.Tests/Linq/InTest.cs index e9a585b8a2..49939f5956 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/InTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/InTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2009.09.30 @@ -29,10 +29,10 @@ public void StringContainsTest() var query2 = from c in Session.Query.All() where !c.FirstName.In("Michelle", "Jack") select c.Invoices; - var expected1 = from c in Session.Query.All().AsEnumerable() + var expected1 = from c in Customers where !list.Contains(c.FirstName) select c.Invoices; - var expected2 = from c in Session.Query.All().AsEnumerable() + var expected2 = from c in Customers where !c.FirstName.In(list) select c.Invoices; Assert.That(query1, Is.Not.Empty); @@ -69,7 +69,7 @@ public void LongSequenceIntTest() var query2 = from invoice in Session.Query.All() where (invoice.Commission).In(list2) select invoice; - var expected = from invoice in Session.Query.All().AsEnumerable() + var expected = from invoice in Invoices where (invoice.Commission).In(list1) select invoice; Assert.That(query1, Is.Not.Empty); @@ -86,7 +86,7 @@ public void IntAndDecimalContains1Test() var query = from invoice in Session.Query.All() where !((int) invoice.Commission).In(list) select invoice; - var expected = from invoice in Session.Query.All().AsEnumerable() + var expected = from invoice in Invoices where !((int) invoice.Commission).In(list) select invoice; Assert.That(query, Is.Not.Empty); @@ -101,7 +101,7 @@ public void SimpleIntContainsTest() var query = from track in Session.Query.All() where track.Milliseconds.In(list) select track; - var expected = from track in Session.Query.All().AsEnumerable() + var expected = from track in Tracks where track.Milliseconds.In(list) select track; Assert.That(query, Is.Not.Empty); @@ -133,7 +133,7 @@ public void IntAndDecimalContains2Test() var query = from invoice in Session.Query.All() where !((decimal) invoice.InvoiceId).In(list) select invoice; - var expected = from invoice in Session.Query.All().AsEnumerable() + var expected = from invoice in Invoices where !((decimal) invoice.InvoiceId).In(list) select invoice; Assert.That(query, Is.Not.Empty); @@ -148,7 +148,7 @@ public void EntityContainsTest() var query = from c in Session.Query.All() where !c.In(list) select c.Invoices; - var expected = from c in Session.Query.All().AsEnumerable() + var expected = from c in Customers where !c.In(list) select c.Invoices; Assert.That(query, Is.Not.Empty); @@ -163,7 +163,7 @@ public void StructContainsTest() var query = from c in Session.Query.All() where !c.Address.In(list) select c.Invoices; - var expected = from c in Session.Query.All().AsEnumerable() + var expected = from c in Customers where !c.Address.In(list) select c.Invoices; Assert.That(query, Is.Not.Empty); @@ -184,7 +184,7 @@ public void AnonimousContainsTest() { var list = new[] {new {FirstName = "Michelle"}, new {FirstName = "Jack"}}; var query = Session.Query.All().Where(c => new {c.FirstName}.In(list)).Select(c => c.Invoices); - var expected = Session.Query.All().AsEnumerable().Where(c => new {c.FirstName}.In(list)).Select(c => c.Invoices); + var expected = Customers.Where(c => new {c.FirstName}.In(list)).Select(c => c.Invoices); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); QueryDumper.Dump(query); @@ -195,7 +195,7 @@ public void AnonimousContains2Test() { var list = new[] {new {Id1 = "Michelle", Id2 = "Michelle"}, new {Id1 = "Jack", Id2 = "Jack"}}; var query = Session.Query.All().Where(c => new {Id1 = c.FirstName, Id2 = c.FirstName}.In(list)).Select(c => c.Invoices); - var expected = Session.Query.All().AsEnumerable().Where(c => new {Id1 = c.FirstName, Id2 = c.FirstName}.In(list)).Select(c => c.Invoices); + var expected = Customers.Where(c => new {Id1 = c.FirstName, Id2 = c.FirstName}.In(list)).Select(c => c.Invoices); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); QueryDumper.Dump(query); @@ -211,7 +211,7 @@ public void QueryableDoubleContainsTest() var query = from invoice in Session.Query.All() where !invoice.Commission.In(list) select invoice; - var expected = from invoice in Session.Query.All().AsEnumerable() + var expected = from invoice in Invoices where !invoice.Commission.In(list) select invoice; Assert.That(query, Is.Not.Empty); @@ -226,7 +226,7 @@ public void QueryableEntityContainsTest() var query = from c in Session.Query.All() where !c.In(list) select c.Invoices; - var expected = from c in Session.Query.All().AsEnumerable() + var expected = from c in Customers where !c.In(list) select c.Invoices; Assert.That(query, Is.Not.Empty); @@ -243,7 +243,7 @@ public void QueryableStructContainsTest() var query = from c in Session.Query.All() where !c.Address.In(list) select c.Invoices; - var expected = from c in Session.Query.All().AsEnumerable() + var expected = from c in Customers where !c.Address.In(list) select c.Invoices; Assert.That(query, Is.Not.Empty); @@ -256,7 +256,7 @@ public void QueryableAnonimousContainsTest() { var list = Session.Query.All().Take(10).Select(c => new {c.FirstName}); var query = Session.Query.All().Where(c => new {c.FirstName}.In(list)).Select(c => c.Invoices); - var expected = Session.Query.All().AsEnumerable().Where(c => new {c.FirstName}.In(list)).Select(c => c.Invoices); + var expected = Customers.Where(c => new {c.FirstName}.In(list)).Select(c => c.Invoices); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); QueryDumper.Dump(query); @@ -278,7 +278,7 @@ public void ComplexCondition1Test() var query = from track in Session.Query.All() where track.Milliseconds.In(includeAlgorithm, list) select track; - var expected = from track in Session.Query.All().AsEnumerable() + var expected = from track in Tracks where track.Milliseconds.In(includeAlgorithm, list) select track; Assert.That(query, Is.Not.Empty); @@ -293,7 +293,7 @@ public void ComplexCondition2Test() var query = from track in Session.Query.All() where track.Milliseconds.In(includeAlgorithm, 276192, 349492, 232463) select track; - var expected = from track in Session.Query.All().AsEnumerable() + var expected = from track in Tracks where track.Milliseconds.In(includeAlgorithm, 276192, 349492, 232463) select track; Assert.That(query, Is.Not.Empty); @@ -318,9 +318,9 @@ public void CompiledInTest() Assert.AreEqual("Leonie", result2[0]); } - private static IEnumerable GetCustomers(params string[] customerNames) + private IEnumerable GetCustomers(params string[] customerNames) { - return Session.Demand().Query.Execute(qe => qe.All().Where(customer => customer.FirstName.In(customerNames))); + return Session.Query.Execute(qe => qe.All().Where(customer => customer.FirstName.In(customerNames))); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Linq/IndexedMethodsTest.cs b/Orm/Xtensive.Orm.Tests/Linq/IndexedMethodsTest.cs index 862dfbebf1..722c00dac7 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/IndexedMethodsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/IndexedMethodsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2009.12.14 @@ -26,7 +26,7 @@ protected override void CheckRequirements() public void SelectIndexedTest() { var result = Session.Query.All().OrderBy(i => i.InvoiceId).Select((invoice, index) => new {invoice, index}).ToList(); - var expected = Session.Query.All().AsEnumerable().OrderBy(i => i.InvoiceId).Select((invoice, index) => new {invoice, index}).ToList(); + var expected = Invoices.OrderBy(i => i.InvoiceId).Select((invoice, index) => new {invoice, index}).ToList(); Assert.That(result, Is.Not.Empty); Assert.IsTrue(expected.SequenceEqual(result)); } @@ -45,12 +45,11 @@ public void SelectIndexedWhereTest() [Test] public void SelectManyIndexedTest() { - var count = Session.Query.All().Count(); + var count = Customers.Count(); var result = Session.Query.All() .OrderBy(customer=>customer.LastName) .SelectMany((customer, index) => customer.Invoices.OrderBy(i=>i.InvoiceId).Select(invoice=>new {index, invoice.Commission})); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Customers .OrderBy(customer=>customer.LastName) .SelectMany((customer, index) => customer.Invoices.OrderBy(i=>i.InvoiceId).Select(invoice=>new {index, invoice.Commission})); Assert.That(result, Is.Not.Empty); @@ -66,8 +65,7 @@ public void SelectManyIndexedResultSelectorTest() .SelectMany( (customer, index) => customer.Invoices.OrderBy(i => i.InvoiceId).Select(invoice => new {index, invoice.Commission}), (customer, takenInvoices) => new {customer, takenInvoices}); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Customers .OrderBy(customer => customer.LastName) .SelectMany( (customer, index) => customer.Invoices.OrderBy(i => i.InvoiceId).Select(invoice => new {index, invoice.Commission}), diff --git a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SimpleTest.cs b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SimpleTest.cs index 6693b2db1c..d0ee06a289 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SimpleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SimpleTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexander Nikolaev // Created: 2009.06.01 @@ -28,7 +28,7 @@ public class DTO [Test] public void QueryTest() { - var expected = Session.Query.All().Count(); + var expected = Invoices.Count(); var result = Session.Query.All().ToList(); Assert.AreEqual(expected, result.Count); Assert.IsTrue(result.All(i => i!=null)); @@ -81,7 +81,7 @@ public void ComplexQueryOfUnknownTypeTest() public void QueryByInterfaceTest() { var actual = Session.Query.All().ToList(); - var expected = Session.Query.All().ToList(); + var expected = Invoices; Assert.AreEqual(0, expected.Except(actual.Cast()).Count()); } } diff --git a/Orm/Xtensive.Orm.Tests/Linq/JoinTest.cs b/Orm/Xtensive.Orm.Tests/Linq/JoinTest.cs index ae9c275990..dd60c3db2d 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/JoinTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/JoinTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kochetov // Created: 2008.12.17 @@ -41,7 +41,7 @@ public void EntityJoinWithNullTest() .Select(t => t.TrackId==id ? null : t) .Select(t => t==null ? null : t.MediaType) .ToList(); - var expected = Session.Query.All().ToList() + var expected = Tracks .Select(t => t.TrackId==id ? null : t) .Select(t => t==null ? null : t.MediaType).ToList(); Assert.That(result, Is.Not.Empty); @@ -57,7 +57,7 @@ public void EntityJoinWithNullModifiedTest() (t.TrackId==id) && (t!=null) ? t.MediaType /*exception*/ : (t.TrackId!=id) && (t==null) ? null : t.MediaType) .ToList(); - var expected = Session.Query.All().ToList() + var expected = Tracks .Select(p=>p.TrackId==id ? null : p) .Select(p=>p==null ? null : p.MediaType) .ToList(); @@ -76,8 +76,8 @@ join i in Session.Query.All() on c equals i.Customer into invoices join e in Session.Query.All() on c.Address.City equals e.Address.City into emps select new {invoices = invoices.Count(), emps = emps.Count()}; var list = result.ToList(); - var expected = - Session.Query.All().Select(c => new { + var expected = Customers + .Select(c => new { invoices = (int) c.Invoices.Count, emps = Session.Query.All().Where(e => c.Address.City==e.Address.City).Count() }).ToList(); @@ -104,12 +104,12 @@ public void GroupJoinAggregate2Test() }).OrderBy(t => t.emps).ThenBy(t => t.invoices).ThenBy(t => t.sum); var list = result.ToList(); - var expected = Session.Query.All().AsEnumerable() - .GroupJoin(Session.Query.All().AsEnumerable(), + var expected = Customers + .GroupJoin(Invoices, customer => customer.CustomerId, invoice => invoice.Customer.CustomerId, (customer, invoices) => new {customer, invoices}) - .GroupJoin(Session.Query.All().AsEnumerable(), + .GroupJoin(Employees, customerInvoices => customerInvoices.customer.Address.City, employee => employee.Address.City, (customerInvoices, employees) => new { @@ -247,7 +247,7 @@ join i in Session.Query.All() public void JoinByCalculatedColumnTest() { var customers = Session.Query.All(); - var localCustomers = customers.ToList(); + var localCustomers = Customers.ToList(); var expected = from c1 in localCustomers join c2 in localCustomers @@ -275,8 +275,8 @@ into groups select groups; var expected = - from mediaType in Session.Query.All().AsEnumerable() - join track in Session.Query.All().AsEnumerable() + from mediaType in MediaTypes + join track in Tracks on mediaType equals track.MediaType into groups select groups; diff --git a/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsTest.cs b/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsTest.cs index 9bc87c0e90..06fa4c9f11 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2009.09.07 @@ -186,7 +186,7 @@ public void ListContainsTest() var query = from c in Session.Query.All() where !list.Contains(c.FirstName) select c.Invoices; - var expected = from c in Session.Query.All().AsEnumerable() + var expected = from c in Customers where !list.Contains(c.FirstName) select c.Invoices; Assert.That(list, Is.Not.Empty); @@ -226,7 +226,7 @@ public void PairTest() .ToList(); var query = Session.Query.All() .Join(pairs, customer => customer.LastName, pair => pair.First, (customer, pair) => new {customer, pair.Second}); - var expected = Session.Query.All().AsEnumerable() + var expected = Customers .Join(pairs, customer => customer.LastName, pair => pair.First, (customer, pair) => new {customer, pair.Second}); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -254,12 +254,12 @@ public void Pair2Test() public void Poco1Test() { Assert.Throws(() => { - var pocos = Session.Query.All() + var pocos = Customers .Select(customer => new Poco() { Value = customer.LastName }) .ToList(); var query = Session.Query.All() .Join(pocos, customer => customer.LastName, poco => poco.Value, (customer, poco) => poco); - var expected = Session.Query.All().AsEnumerable() + var expected = Customers .Join(pocos, customer => customer.LastName, poco => poco.Value, (customer, poco) => poco); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -276,7 +276,7 @@ public void Poco2Test() .ToList(); var query = Session.Query.All() .Join(pocos, customer => customer.LastName, poco => poco.Value1, (customer, poco) => poco.Value1); - var expected = Session.Query.All().AsEnumerable() + var expected = Customers .Join(pocos, customer => customer.LastName, poco => poco.Value1, (customer, poco) => poco.Value1); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -289,8 +289,7 @@ public void Poco3Test() var query = Session.Query.All() .Select(customer => new Poco{Value1 = customer.LastName, Value2 = customer.LastName}) .Select(poco=>new {poco.Value1, poco.Value2}); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Customers .Select(customer => new Poco{Value1 = customer.LastName, Value2 = customer.LastName}) .Select(poco=>new {poco.Value1, poco.Value2}); Assert.That(query, Is.Not.Empty); @@ -304,8 +303,7 @@ public void Poco4Test() var query = Session.Query.All() .Select(customer => new Poco(customer.LastName, customer.LastName)) .Select(poco=>new {poco.Value1, poco.Value2}); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Customers .Select(customer => new Poco{Value1 = customer.LastName, Value2 = customer.LastName}) .Select(poco=>new {poco.Value1, poco.Value2}); Assert.That(query, Is.Not.Empty); @@ -320,7 +318,7 @@ public void ArrayContainsTest() var query = from c in Session.Query.All() where !list.Contains(c.FirstName) select c.Invoices; - var expected = from c in Session.Query.All().AsEnumerable() + var expected = from c in Customers where !list.Contains(c.FirstName) select c.Invoices; Assert.That(query, Is.Not.Empty); @@ -335,7 +333,7 @@ public void IListContainsTest() var query = from c in Session.Query.All() where !list.Contains(c.FirstName) select c.Invoices; - var expected = from c in Session.Query.All().AsEnumerable() + var expected = from c in Customers where !list.Contains(c.FirstName) select c.Invoices; Assert.That(query, Is.Not.Empty); @@ -370,7 +368,7 @@ public void ContainsTest() .Where(invoice => localInvoiceCommissions.Contains(invoice.Commission)); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable() + var expectedQuery = Invoices .Where(invoice => localInvoiceCommissions.Contains(invoice.Commission)); Assert.AreEqual(0, expectedQuery.Except(query).Count()); } @@ -383,7 +381,7 @@ public void AnyTest() .Where(invoice => localInvoiceCommissions.Any(commission => commission==invoice.Commission)); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable() + var expectedQuery = Invoices .Where(invoice => localInvoiceCommissions.Any(commission => commission==invoice.Commission)); Assert.AreEqual(0, expectedQuery.Except(query).Count()); } @@ -397,7 +395,7 @@ public void AllTest() .Where(invoice => localInvoiceCommissions.All(commission => commission!=invoice.Commission)); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable() + var expectedQuery = Invoices .Where(invoice => localInvoiceCommissions.All(commission => commission!=invoice.Commission)); Assert.AreEqual(0, expectedQuery.Except(query).Count()); } @@ -411,7 +409,7 @@ public void KeyTest() .Join(keys, invoice => invoice.Key, key => key, (invoice, key) => new {invoice, key}); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable() + var expectedQuery = Invoices .Join(keys, invoice => invoice.Key, key => key, (invoice, key) => new {invoice, key}); Assert.AreEqual(0, expectedQuery.Except(query).Count()); }); @@ -429,7 +427,7 @@ public void JoinEntityTest() (invoice, localInvoice) => new {invoice, localInvoice}); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable().Join( + var expectedQuery = Invoices.Join( localInvoices, invoice => invoice, localInvoice => localInvoice, @@ -450,7 +448,7 @@ public void JoinEntityFieldTest() (invoice, localInvoice) => new {invoice, localInvoice}); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable().Join( + var expectedQuery = Invoices.Join( localInvoices, invoice => invoice.Commission, localInvoice => localInvoice.Commission, @@ -470,7 +468,7 @@ public void JoinEntityField2Test() (invoice, commission) => new {invoice, commission}); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable().Join( + var expectedQuery = Invoices.Join( localCommissions, invoice => invoice.Commission, commission => commission, @@ -490,7 +488,7 @@ public void JoinEntityField2MaterializeTest() (invoice, commission) => new {invoice, commission}).Select(x => x.commission); Assert.That(query, Is.Not.Empty); QueryDumper.Dump(query); - var expectedQuery = Session.Query.All().AsEnumerable().Join( + var expectedQuery = Invoices.Join( localCommissions, invoice => invoice.Commission, commission => commission, @@ -549,8 +547,7 @@ public void SimpleIntersectTest() .Select(i => i.DesignatedEmployee.BirthDate) .Intersect(Session.Query.All().ToList().Select(i => i.DesignatedEmployee.BirthDate)); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Invoices .Select(i => i.DesignatedEmployee.BirthDate) .Intersect(Session.Query.All().ToList().Select(i => i.DesignatedEmployee.BirthDate)); @@ -568,8 +565,7 @@ public void SimpleIntersectEntityTest() .Select(i => i.DesignatedEmployee) .Intersect(Session.Query.All().ToList().Select(i => i.DesignatedEmployee)); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Invoices .Select(i => i.DesignatedEmployee) .Intersect(Session.Query.All().ToList().Select(i => i.DesignatedEmployee)); @@ -877,7 +873,7 @@ public void Aggregate2Test() var queryable = Session.Query.Store(localItems); var result = Session.Query.All() .Where(invoice => invoice.Commission > queryable.Max(poco=>poco.Value2)); - var expected = Session.Query.All().AsEnumerable() + var expected = Invoices .Where(invoice => invoice.Commission > localItems.Max(poco=>poco.Value2)); Assert.That(result, Is.Not.Empty); diff --git a/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs b/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs index 8af862be42..e9c69b3cb2 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/OrderByTest.cs @@ -56,7 +56,7 @@ public void OrderByAnonymousEntityTest() .OrderBy(x => new {x, x.Invoice.Customer}) .Select(x => new {x, x.Invoice.Customer}); - var expected = Session.Query.All().ToList() + var expected = InvoiceLines .Select(il => new {InvoiceLine = il, Invoice = il.Invoice}) .OrderBy(x => x.InvoiceLine.InvoiceLineId) .ThenBy(x => x.Invoice.InvoiceId) @@ -139,8 +139,8 @@ from c in Session.Query.All().OrderBy(c => c.LastName) join i in Session.Query.All().OrderBy(i => i.InvoiceDate) on c equals i.Customer select new {c.LastName, i.InvoiceDate}; var expected = - from c in Session.Query.All().ToList().OrderBy(c => c.LastName) - join i in Session.Query.All().ToList().OrderBy(i => i.InvoiceDate) on c equals i.Customer + from c in Customers.OrderBy(c => c.LastName) + join i in Invoices.OrderBy(i => i.InvoiceDate) on c equals i.Customer select new {c.LastName, i.InvoiceDate}; Assert.That(result, Is.Not.Empty); Assert.IsTrue(expected.SequenceEqual(result)); @@ -179,7 +179,7 @@ public void OrderBySelectAnonymousTest() var result = Session.Query.All() .OrderBy(c => c.CustomerId) .Select(c => new {c.Fax, c.Phone}); - var expected = Customers.ToList() + var expected = Customers .OrderBy(c => c.CustomerId) .Select(c => new {c.Fax, c.Phone}); Assert.That(result, Is.Not.Empty); @@ -195,8 +195,8 @@ from i in Session.Query.All().OrderBy(i => i.InvoiceDate) where c==i.Customer select new {c.LastName, i.InvoiceDate}; var expected = - from c in Session.Query.All().ToList().OrderBy(c => c.LastName) - from i in Session.Query.All().ToList().OrderBy(i => i.InvoiceDate) + from c in Customers.OrderBy(c => c.LastName) + from i in Invoices.OrderBy(i => i.InvoiceDate) where c==i.Customer select new {c.LastName, i.InvoiceDate}; Assert.That(result, Is.Not.Empty); @@ -208,7 +208,7 @@ public void OrderBySelectTest() { IQueryable result = Session.Query.All().OrderBy(c => c.CompanyName) .OrderBy(c => c.Address.Country).Select(c => c.Address.City); - var expected = Session.Query.All().ToList().OrderBy(c => c.CompanyName) + var expected = Customers.OrderBy(c => c.CompanyName) .OrderBy(c => c.Address.Country).Select(c => c.Address.City); Assert.That(result, Is.Not.Empty); Assert.AreEqual(0, expected.Except(result).Count()); @@ -223,8 +223,7 @@ public void SequentialOrderByTest() .Distinct() .OrderBy(c => c) .Select(c => c); - var expected = Session.Query.All() - .ToList() + var expected = Customers .Select(c => c.Address.City) .Distinct() .OrderBy(c => c) @@ -238,7 +237,7 @@ public void DistinctTest() { Require.ProviderIsNot(StorageProvider.SqlServerCe); var result = Session.Query.All().Select(i => i.DesignatedEmployee).Distinct(); - var expected = Session.Query.All().ToList().Select(i => i.DesignatedEmployee).Distinct(); + var expected = Invoices.Select(i => i.DesignatedEmployee).Distinct(); Assert.That(result, Is.Not.Empty); Assert.AreEqual(0, result.ToList().Except(expected).Count()); } diff --git a/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs b/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs index 948c665b18..83833e635e 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs @@ -1,11 +1,13 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2010-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2010.01.15 using System.Linq; using NUnit.Framework; +using Xtensive.Collections; +using Xtensive.Core; using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.ObjectModel; using Xtensive.Orm.Tests.ObjectModel.ChinookDO; @@ -30,9 +32,7 @@ public void SingleSubqueryNonGenericTest() { var query = Session.Query.All() .Where(c => c==Session.Query.Single(Session.Query.All().FirstOrDefault().Key)); - var expected = Session.Query.All().AsEnumerable() - .Where(c => c==Session.Query.Single(Session.Query.All().FirstOrDefault().Key)); - Assert.Throws(() => Assert.AreEqual(0, expected.Except(query).Count())); + _ = Assert.Throws(() => query.Run()); } [Test] @@ -41,8 +41,7 @@ public void SingleSubqueryKeyTest() Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() .Where(c => c==Session.Query.Single(Session.Query.All().FirstOrDefault().Key)); - var expected = Session.Query.All().AsEnumerable() - .Where(c => c==Session.Query.Single(Session.Query.All().FirstOrDefault().Key)); + var expected = EnumerableUtils.One(Customers.First()); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -53,9 +52,7 @@ public void SingleSubqueryTupleTest() { var query = Session.Query.All() .Where(c => c == Session.Query.Single(Session.Query.All().FirstOrDefault().CustomerId)); - var expected = Session.Query.All().AsEnumerable() - .Where(c => c == Session.Query.Single(Session.Query.All().FirstOrDefault().CustomerId)); - Assert.Throws(() => Assert.AreEqual(0, expected.Except(query).Count())); + _ = Assert.Throws(() => query.Run()); } [Test] @@ -64,8 +61,7 @@ public void SingleOrDefaultParameterTest() var key = Session.Query.All().First().Key; var query = Session.Query.All() .Where(c => c==Session.Query.SingleOrDefault(key)); - var expected = Session.Query.All().AsEnumerable() - .Where(c => c==Session.Query.SingleOrDefault(key)); + var expected = Customers.Where(c => c.Key == key); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -76,9 +72,7 @@ public void SingleOrDefaultSubqueryNonGenericTest() { var query = Session.Query.All() .Where(c => c==Session.Query.SingleOrDefault(Session.Query.All().FirstOrDefault().Key)); - var expected = Session.Query.All().AsEnumerable() - .Where(c => c==Session.Query.SingleOrDefault(Session.Query.All().FirstOrDefault().Key)); - Assert.Throws(() => Assert.AreEqual(0, expected.Except(query).Count())); + _ = Assert.Throws(() => query.Run()); } [Test] @@ -87,8 +81,7 @@ public void SingleOrDefaultSubqueryKeyTest() Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() .Where(c => c==Session.Query.SingleOrDefault(Session.Query.All().FirstOrDefault().Key)); - var expected = Session.Query.All().AsEnumerable() - .Where(c => c==Session.Query.SingleOrDefault(Session.Query.All().FirstOrDefault().Key)); + var expected = EnumerableUtils.One(Customers.First()); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -99,9 +92,7 @@ public void SingleOrDefaultSubqueryTupleTest() { var query = Session.Query.All() .Where(c => c==Session.Query.SingleOrDefault(Session.Query.All().FirstOrDefault().CustomerId)); - var expected = Session.Query.All().AsEnumerable() - .Where(c => c==Session.Query.SingleOrDefault(Session.Query.All().FirstOrDefault().CustomerId)); - Assert.Throws(() => Assert.AreEqual(0, expected.Except(query).Count())); + _ = Assert.Throws(() => query.Run()); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Linq/SelectManyTest.cs b/Orm/Xtensive.Orm.Tests/Linq/SelectManyTest.cs index 0d7d9149a6..56a6dcb821 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/SelectManyTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/SelectManyTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 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 // Created: 2009.04.01 @@ -34,8 +34,8 @@ public void GroupJoinTest() Country = x.Address.Country }) ; - var expected = Session.Query.All().AsEnumerable() - .GroupJoin(Session.Query.All().AsEnumerable(), + var expected = Invoices + .GroupJoin(Customers, i => i.Customer, c => c, (i, ic) => new {i, ic}) @@ -60,7 +60,7 @@ public void GroupByTest() .GroupBy(i => i.Customer) .SelectMany(g => g); var list = result.ToList(); - var expected = Session.Query.All().ToList(); + var expected = Invoices; Assert.That(list, Is.Not.Empty); Assert.IsTrue(list.Except(expected).IsNullOrEmpty()); } @@ -74,7 +74,7 @@ public void GroupBy2Test() var result = Session.Query.All() .GroupBy(i => i.Customer) .SelectMany(g => g, (grouping, invoice)=>new {Count = grouping.Count(), Invoice = invoice}); - var expected = Session.Query.All().ToList() + var expected = Invoices .GroupBy(i => i.Customer) .SelectMany(g => g, (grouping, invoice)=>new {Count = grouping.Count(), Invoice = invoice}); var list = result.ToList(); @@ -92,7 +92,7 @@ public void GroupBySelectorTest() .SelectMany(g => g.Select(i => i.Customer)); var list = result.ToList(); Assert.That(list, Is.Not.Empty); - var expected = Session.Query.All().Select(i => i.Customer).ToList(); + var expected = Invoices.Select(i => i.Customer); Assert.IsTrue(list.Except(expected).IsNullOrEmpty()); } @@ -104,10 +104,9 @@ public void GroupByCountTest() .GroupBy(i => i.Customer) .SelectMany(g => g.Select(i => i.Customer).Where(c => g.Count() > 2)); var list = result.ToList(); - var expected = Session.Query.All().ToList() + var expected = Invoices .GroupBy(i => i.Customer) - .SelectMany(g => g.Select(i => i.Customer).Where(c => g.Count() > 2)) - .ToList(); + .SelectMany(g => g.Select(i => i.Customer).Where(c => g.Count() > 2)); Assert.That(list, Is.Not.Empty); Assert.IsTrue(list.Except(expected).IsNullOrEmpty()); @@ -122,10 +121,9 @@ public void GroupByCount2Test() .Where(g => g.Count() > 2) .SelectMany(g => g.Select(i => i.Customer)); var list = result.ToList(); - var expected = Session.Query.All().ToList() + var expected = Invoices .GroupBy(i => i.Customer) - .SelectMany(g => g.Select(i => i.Customer).Where(c => g.Count() > 2)) - .ToList(); + .SelectMany(g => g.Select(i => i.Customer).Where(c => g.Count() > 2)); Assert.That(list, Is.Not.Empty); Assert.IsTrue(list.Except(expected).IsNullOrEmpty()); @@ -134,7 +132,7 @@ public void GroupByCount2Test() [Test] public void ParameterTest() { - var expectedCount = Session.Query.All().Count(); + var expectedCount = Invoices.Count(); var result = Session.Query.All() .SelectMany(i => i.Invoices.Select(t => i)); @@ -185,7 +183,7 @@ public void EntitySetSubqueryWithResultSelectorTest() [Test] public void EntitySetTest() { - int expected = Session.Query.All().Count(); + int expected = Invoices.Count(); IQueryable result = Session.Query.All() .SelectMany(c => c.Invoices); @@ -197,7 +195,7 @@ public void EntitySetTest() public void EntitySetWithCastTest() { var result = Session.Query.All().SelectMany(c => (IEnumerable) c.Invoices).ToList(); - var expected = Session.Query.All().ToList(); + var expected = Invoices; Assert.That(result, Is.Not.Empty); Assert.IsTrue(result.Except(expected).IsNullOrEmpty()); @@ -207,7 +205,7 @@ public void EntitySetWithCastTest() public void SelectManyWithCastTest() { var result = Session.Query.All().SelectMany(c => (IEnumerable) Session.Query.All().Where(i => i.Customer==c)).ToList(); - var expected = Session.Query.All().ToList(); + var expected = Invoices; Assert.That(result, Is.Not.Empty); Assert.IsTrue(result.Except(expected).IsNullOrEmpty()); @@ -334,7 +332,7 @@ public void SelectManyAfterSelect1Test() [Test] public void SelectManyAfterSelect2Test() { - int expected = Session.Query.All().Count(); + int expected = Invoices.Count(); IQueryable result = Session.Query.All() .Select(c => Session.Query.All().Where(i => i.Customer==c)).SelectMany(i => i); @@ -345,7 +343,7 @@ public void SelectManyAfterSelect2Test() [Test] public void SimpleTest() { - int expected = Session.Query.All().Count(); + int expected = Invoices.Count(); IQueryable result = Session.Query.All() .SelectMany(c => Session.Query.All().Where(i => i.Customer==c)); @@ -356,7 +354,7 @@ public void SimpleTest() [Test] public void SimpleWithResultSelectorTest() { - var expected = Session.Query.All().Count(); + var expected = Invoices.Count(); var result = Session.Query.All() .SelectMany(c => Session.Query.All().Where(i => i.Customer==c), (c, i) => new {c, i}); @@ -445,7 +443,7 @@ from i in (c.Invoices.Select(x => c.FirstName + x.BillingAddress.StreetAddress). orderby i select i; - var expected = from c in Session.Query.All().ToList() + var expected = from c in Customers from i in (c.Invoices.Select(x => c.FirstName + x.BillingAddress.StreetAddress).Where(x => x.StartsWith("M"))) orderby i select i; @@ -465,7 +463,7 @@ from n in (c.Invoices.Select(i => c.FirstName + i.BillingAddress.StreetAddress)) orderby n select n; - var expected = from c in Session.Query.All().ToList() + var expected = from c in Customers from n in (c.Invoices.Select(i => c.FirstName + i.BillingAddress.StreetAddress)) .Union(c.Invoices.Select(i => c.FirstName + i.BillingAddress.StreetAddress)) orderby n @@ -484,7 +482,7 @@ from i in (c.Invoices.Where(x => x.BillingAddress.StreetAddress.StartsWith("A")) .Intersect(c.Invoices.Where(x => x.BillingAddress.StreetAddress.StartsWith("A")))) orderby i.InvoiceId select i.InvoiceId; - var expected = from c in Session.Query.All().ToList() + var expected = from c in Customers from i in (c.Invoices.Where(x => x.BillingAddress.StreetAddress.StartsWith("A")).Intersect(c.Invoices)) orderby i.InvoiceId select i.InvoiceId; diff --git a/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs b/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs index abacf2e574..f89afab8b4 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/SelectTest.cs @@ -60,9 +60,7 @@ public void IndexerSimpleFieldTest() .OrderBy(customer => customer.CustomerId) .Select(customer => customer["Phone"]) .AsEnumerable(); - var expected = Session.Query - .All() - .AsEnumerable() + var expected = Customers .OrderBy(customer => customer.CustomerId) .Select(customer => customer["Phone"]); Assert.IsTrue(expected.SequenceEqual(result)); @@ -87,9 +85,7 @@ public void IndexerEntityTest() .OrderBy(invoice => invoice.InvoiceId) .Select(invoice => invoice["Customer"]) .AsEnumerable(); - var expected = Session.Query - .All() - .AsEnumerable() + var expected = Invoices .OrderBy(invoice => invoice.InvoiceId) .Select(invoice => invoice["Customer"]); Assert.IsTrue(expected.SequenceEqual(result)); @@ -103,9 +99,7 @@ public void IndexerStructureTest() .OrderBy(customer => customer.CustomerId) .Select(customer => customer["Address"]) .AsEnumerable(); - var expected = Session.Query - .All() - .AsEnumerable() + var expected = Customers .OrderBy(customer => customer.CustomerId) .Select(customer => customer["Address"]); Assert.IsTrue(expected.SequenceEqual(result)); @@ -172,7 +166,7 @@ public void SelectForeignFieldTest() public void SelectUsingContextTest() { Require.ProviderIsNot(StorageProvider.SqlServerCe | StorageProvider.Oracle); - var expectedCount = Session.Query.All().Count(); + var expectedCount = Invoices.Count(); var context = new Context(); var actualCount = context.Invoices.Count(); var list = context.Invoices.ToList(); @@ -790,9 +784,7 @@ public void SelectStringIndexerTest() .ToArray() .OrderBy(item => item.String) .ToArray(); - var expected = - Session.Query.All() - .ToArray() + var expected = Customers .Select(c => new { String = c.CustomerId, Char0 = c.Email[0], @@ -832,9 +824,7 @@ public void SelectIndexOfTest() .ToArray() .OrderBy(item => item.String) .ToArray(); - var expected = - Session.Query.All() - .ToArray() + var expected = Customers .Select(c => new { String = c.FirstName, IndexOfChar = c.FirstName.IndexOf(_char), @@ -867,9 +857,7 @@ public void SelectStringContainsTest1() .Where(c => c.FirstName.Contains('L')) .OrderBy(c => c.CustomerId) .ToArray(); - var expected = - Session.Query.All() - .ToList() + var expected = Customers .Where(c => c.FirstName.Contains('L') || c.FirstName.Contains('l')) .OrderBy(c => c.CustomerId) .ToArray(); @@ -885,9 +873,7 @@ public void SelectStringContainsTest2() .Where(c => c.FirstName.Contains('L')) .OrderBy(c => c.CustomerId) .ToArray(); - var expected = - Session.Query.All() - .ToList() + var expected = Customers .Where(c => c.FirstName.Contains('L')) .OrderBy(c => c.CustomerId) .ToArray(); @@ -995,8 +981,7 @@ public void ExternalMethodCall() Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() .Select(c => GetCustomers().Single(c2 => c2 == c)); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Customers .Select(c => GetCustomers().AsEnumerable().Single(c2 => c2 == c)); Assert.AreEqual(0, expected.Except(query).Count()); } @@ -1007,8 +992,7 @@ public void ExternalMethodWithCorrectParams1Call() Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() .Select(c => GetCustomers(1).Single(c2 => c2 == c)); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Customers .Select(c => GetCustomers(1).AsEnumerable().Single(c2 => c2 == c)); Assert.AreEqual(0, expected.Except(query).Count()); } @@ -1020,8 +1004,7 @@ public void ExternalMethodWithCorrectParams2Call() var count = 1; var query = Session.Query.All() .Select(c => GetCustomers(count).Single(c2 => c2 == c)); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Customers .Select(c => GetCustomers(count).AsEnumerable().Single(c2 => c2 == c)); Assert.AreEqual(0, expected.Except(query).Count()); } diff --git a/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs b/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs index dcd268ea00..25b5c9bd4d 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Elena Vakhtina // Created: 2009.04.06 @@ -242,7 +242,7 @@ from r in (c.Invoices) .Intersect(c.Invoices).Select(o => o.PaymentDate) orderby r select r; - var expected = from c in Session.Query.All().ToList() + var expected = from c in Customers from r in (c.Invoices) .Intersect(c.Invoices).Select(o => o.PaymentDate) orderby r diff --git a/Orm/Xtensive.Orm.Tests/Linq/WhereTest.cs b/Orm/Xtensive.Orm.Tests/Linq/WhereTest.cs index ada53c8bea..682419b42d 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/WhereTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/WhereTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kochetov // Created: 2008.12.13 @@ -98,9 +98,7 @@ public void IndexerSimpleFieldTest() .OrderBy(invoice => invoice.InvoiceId) .Where(invoice => invoice["Commission"]==freight) .ToList(); - var expected = Session.Query - .All() - .AsEnumerable() + var expected = Invoices .OrderBy(invoice => invoice.InvoiceId) .Where(invoice => invoice.Commission==(decimal?) freight) .ToList(); @@ -120,9 +118,7 @@ public void IndexerStructureTest() .Where(customer => customer["Address"]==address) .ToList(); #pragma warning disable 252,253 - var expected = Session.Query - .All() - .AsEnumerable() + var expected = Customers .OrderBy(customer => customer.CustomerId) .Where(customer => customer.Address==address) .ToList(); @@ -142,9 +138,7 @@ public void IndexerEntity1Test() .OrderBy(invoice => invoice.InvoiceId) .Where(invoice => invoice["Customer"]==customer) .ToList(); - var expected = Session.Query - .All() - .AsEnumerable() + var expected = Invoices .OrderBy(invoice => invoice.InvoiceId) .Where(invoice => invoice.Customer==customer) .ToList(); @@ -163,8 +157,7 @@ public void EntitySubqueryTest() .First(invoice2 => invoice2.Customer!=null) .Customer) .ToList(); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Invoices .OrderBy(invoice => invoice.InvoiceId) .Where(invoice => invoice.Customer== Session.Query.All() @@ -187,8 +180,7 @@ public void EntitySubqueryIndexerTest() .First(invoice2 => invoice2["Customer"]!=null) .Customer) .ToList(); - var expected = Session.Query.All() - .AsEnumerable() + var expected = Invoices .OrderBy(invoice => invoice.InvoiceId) .Where(invoice => invoice.Customer== Session.Query.All() @@ -285,7 +277,7 @@ public void Anonymous2Test2() [Test] public void Anonymous3Test() { - var expectedResultCount = Session.Query.All().Count(); + var expectedResultCount = Customers.Count(); var result = Session.Query.All().Where(c => new {c.FirstName, c.LastName}==new {c.FirstName, c.LastName}).ToList(); Assert.That(result.Count, Is.EqualTo(expectedResultCount)); } @@ -315,7 +307,7 @@ public void ColumnTest() [Test] public void CalculatedTest() { - var expected = Session.Query.All().ToList().Where(i => i.Total * i.Commission >= 10).ToList(); + var expected = Invoices.Where(i => i.Total * i.Commission >= 10).ToList(); var actual = Session.Query.All().ToList().Where(i => i.Total * i.Commission >= 10).ToList(); Assert.That(expected.Count, Is.GreaterThan(0)); Assert.AreEqual(expected.Count, actual.Count); @@ -1317,7 +1309,7 @@ where invoice.Commission > 30 orderby new {customer, invoice} select new {customer, invoice}; var list = actual.ToList(); - var expected = from customer in Session.Query.All().ToList() + var expected = from customer in Customers join invoice in Session.Query.All().ToList() on customer equals invoice.Customer where invoice.Commission > 30 orderby customer.CustomerId , invoice.InvoiceId @@ -1330,8 +1322,7 @@ public void ApplyTest() { var actual = Session.Query.All() .Where(customer => customer.Invoices.Any(i => i.Commission > 0.30m)); - var expected = Session.Query.All() - .AsEnumerable() // AG: Just to remeber about it. + var expected = Customers .Where(customer => customer.Invoices.Any(i => i.Commission > 0.30m)); Assert.IsTrue(expected.SequenceEqual(actual)); } diff --git a/Orm/Xtensive.Orm.Tests/Storage/ApplyTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ApplyTest.cs index 59643b30e2..c6ce0fb031 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ApplyTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ApplyTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 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 // Created: 2009.03.20 @@ -41,7 +41,7 @@ private void LoadData(Session session) invoiceCustomerIndex = orderPrimary.Header.IndexOf(invoiceCustomerColumn); allCustomers = customerPrimary.GetRecordSet(session).ToEntities(0).ToList(); - allInvoices = orderPrimary.GetRecordSet(session).ToEntities(0).ToList(); + allInvoices = orderPrimary.GetRecordSet(session).ToEntities(0).ToList(); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs b/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs index 365549d0bd..a7b6fc2b39 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.04.25 @@ -31,7 +31,7 @@ public void CachedSubquerySequenceTest() var addresses = Session.Query.All() .Select(c => c.Address) .ToList(); - var expectedItems = Session.Query.All() + var expectedItems = Customers .Select(c => new {Customer = c, ProductsCount = c.Invoices.Count}) .ToDictionary(a => a.Customer.Address); foreach (var address in addresses) { From c8cae25f830cf853505b767769bc9e579833de0a Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 6 Apr 2021 14:16:01 +0500 Subject: [PATCH 44/71] Workaround for Firebird --- Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs b/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs index 83833e635e..d738627b50 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/QueryMethodTests.cs @@ -4,6 +4,7 @@ // Created by: Alexey Gamzov // Created: 2010.01.15 +using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Xtensive.Collections; @@ -41,7 +42,7 @@ public void SingleSubqueryKeyTest() Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() .Where(c => c==Session.Query.Single(Session.Query.All().FirstOrDefault().Key)); - var expected = EnumerableUtils.One(Customers.First()); + var expected = GetExpectedCustomerAsSequence(); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -81,7 +82,7 @@ public void SingleOrDefaultSubqueryKeyTest() Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); var query = Session.Query.All() .Where(c => c==Session.Query.SingleOrDefault(Session.Query.All().FirstOrDefault().Key)); - var expected = EnumerableUtils.One(Customers.First()); + var expected = GetExpectedCustomerAsSequence(); Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); @@ -139,5 +140,13 @@ public void Store2Test() Assert.That(query, Is.Not.Empty); Assert.AreEqual(0, expected.Except(query).Count()); } + + private IEnumerable GetExpectedCustomerAsSequence() + { + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird)) { + return EnumerableUtils.One(Session.Query.All().OrderBy(c => c.CustomerId).AsEnumerable().First()); + } + return EnumerableUtils.One(Customers.First()); + } } } \ No newline at end of file From 12e2de9ec3adde496ce2538474afb0639bd7d179 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 7 Apr 2021 14:39:55 +0500 Subject: [PATCH 45/71] Some tests fixed for Postgres - Spatial test now expects right value for PgsqlPath (new client library writes to db correct default falue for PgsqlPath.Open) - float accuracy is taken into account for Sum and Average results - Removed Postgres from list of test storages for some test method (see comment in Require) - Rounding test uses special Entities for decimans and doubles - some sabbath word wierdness workarounded --- ...ueJira0593_AggregateForSingleColumnTest.cs | 28 +++++--- Orm/Xtensive.Orm.Tests/Linq/FreeTextTest.cs | 17 +++-- .../PersistWithAsyncQueriesTest.cs | 9 +++ .../Storage/NewProfilesTest.cs | 6 +- .../Storage/PostgreSqlSpatialTest.cs | 12 ++-- .../Storage/Providers/Sql/RoundingTest.cs | 70 ++++++++++--------- .../Storage/TypeCompatibilityTest.cs | 16 ++++- 7 files changed, 102 insertions(+), 56 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs index 1a21552cfd..ab8b162010 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0593_AggregateForSingleColumnTest.cs @@ -118,6 +118,8 @@ public class IssueJira0593_AggregateForSingleColumnTest : AutoBuildTest private const int EntityCount = 20; private const string FilterCondition = "3"; + private const decimal FloatValueAccuracy = 0.00001m; + protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); @@ -584,10 +586,15 @@ private static void CheckQueryable(IQueryable query) private static void CheckQueryable(IQueryable query) { var localArray = query.ToArray(); - Assert.AreEqual(localArray.Sum(), query.Sum(c => c)); - Assert.AreEqual(localArray.Sum(), query.Sum()); - Assert.AreEqual(localArray.Average(), query.Average(c => c)); - Assert.AreEqual(localArray.Average(), query.Average()); + Assert.That(Math.Abs(query.Sum(c => c) - localArray.Sum()), Is.LessThan(FloatValueAccuracy)); + Assert.That(Math.Abs(query.Sum() - localArray.Sum()), Is.LessThan(FloatValueAccuracy)); + //Assert.AreEqual(localArray.Sum(), query.Sum(c => c)); + //Assert.AreEqual(localArray.Sum(), query.Sum()); + + Assert.That(Math.Abs(query.Average(c => c) - localArray.Average()), Is.LessThan(FloatValueAccuracy)); + Assert.That(Math.Abs(query.Average() - localArray.Average()), Is.LessThan(FloatValueAccuracy)); + //Assert.AreEqual(localArray.Average(), query.Average(c => c)); + //Assert.AreEqual(localArray.Average(), query.Average()); Assert.AreEqual(localArray.Min(), query.Min(c => c)); Assert.AreEqual(localArray.Min(), query.Min()); Assert.AreEqual(localArray.Max(), query.Max(c => c)); @@ -598,10 +605,15 @@ private static void CheckQueryable(IQueryable query) private static void CheckQueryable(IQueryable query) { var localArray = query.ToArray(); - Assert.AreEqual(localArray.Sum(), query.Sum(c => c)); - Assert.AreEqual(localArray.Sum(), query.Sum()); - Assert.AreEqual(localArray.Average(), query.Average(c => c)); - Assert.AreEqual(localArray.Average(), query.Average()); + + Assert.That(Math.Abs(query.Sum(c => c).Value - localArray.Sum().Value), Is.LessThan(FloatValueAccuracy)); + Assert.That(Math.Abs(query.Sum().Value - localArray.Sum().Value), Is.LessThan(FloatValueAccuracy)); + //Assert.AreEqual(localArray.Sum(), query.Sum(c => c)); + //Assert.AreEqual(localArray.Sum(), query.Sum()); + Assert.That(Math.Abs(query.Average(c => c).Value - localArray.Average().Value), Is.LessThan(FloatValueAccuracy)); + Assert.That(Math.Abs(query.Average().Value - localArray.Average().Value), Is.LessThan(FloatValueAccuracy)); + //Assert.AreEqual(localArray.Average(), query.Average(c => c)); + //Assert.AreEqual(localArray.Average(), query.Average()); Assert.AreEqual(localArray.Min(), query.Min(c => c)); Assert.AreEqual(localArray.Min(), query.Min()); Assert.AreEqual(localArray.Max(), query.Max(c => c)); diff --git a/Orm/Xtensive.Orm.Tests/Linq/FreeTextTest.cs b/Orm/Xtensive.Orm.Tests/Linq/FreeTextTest.cs index 63225b0564..fe54b7d5df 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/FreeTextTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/FreeTextTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.12.14 @@ -365,7 +365,16 @@ where ft.Entity.TrackId > 0 && ft.Entity.UnitPrice > 0.8m orderby ft.Entity.Album.Title, ft.Entity.UnitPrice select new {Track = ft.Entity, ft.Entity.Name}; var list = result.ToList(); - Assert.AreEqual(26, list.Count); + + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.PostgreSql)) { + // for some reason PosgreSQL does not like the 'sabbath' word. + // there are two tracks with this word in name and they are missing in results. + // direct search by the word also does not show any of these two tracks. + Assert.AreEqual(24, list.Count); + } + else { + Assert.AreEqual(26, list.Count); + } } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs index 37d6341b68..ea9061776e 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/AsyncQueries/PersistWithAsyncQueriesTest.cs @@ -103,6 +103,7 @@ public async Task AsyncButFullySequentialTest() [Test] public async Task QueryFirstWaitLaterTest() { + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands, so having two readers opened is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = session.Query.All().AsAsync(); @@ -128,6 +129,7 @@ public async Task QueryFirstWaitLaterTest() [Test] public async Task QueryFirstWaitLaterInDiffferentOrderTest() { + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands. so having opened reader for query and making changes saved is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()){ var readyToRockQuery = session.Query.All().AsAsync(); @@ -216,6 +218,7 @@ public async Task ProperPersistSequenceFirebirdTest() [Test] public async Task PersistBeforeFirstAsyncQueryAwaitTest() { + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands. so having two readers opened is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { _ = new TestEntity(session); @@ -244,6 +247,7 @@ public async Task PersistBeforeFirstAsyncQueryAwaitTest() public async Task PersistBeforeSecondAsyncQueryAwaitTest() { Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands, so having opened reader for query and making changes saved is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = await session.Query.All().AsAsync(); @@ -300,6 +304,7 @@ public async Task PersistBeforeSecondAsyncQueryAwaitFirebirdTest() public async Task PersistBeforeBothAsyncQueriesAndDelayedWaitTest() { Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands, so having opened reader for query and making changes saved is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { _ = new TestEntity(session) { Value = 101 }; @@ -363,6 +368,7 @@ public async Task PersistBeforeBothAsyncQueriesAndDelayedWaitFirebirdTest() [Test] public async Task PersistBeforeFirstAsyncQueryAndDalayedAwaitTest() { + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands, so having two readers opened is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { _ = new TestEntity(session); @@ -391,6 +397,7 @@ public async Task PersistBeforeFirstAsyncQueryAndDalayedAwaitTest() public async Task PersistBeforeSecondAsyncQueryAndDelayedAwaitTest() { Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands. so having opened reader for query and making changes saved is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = session.Query.All().AsAsync(); @@ -504,6 +511,7 @@ public async Task AwaitingQueryBeforeManualSavingChangesTest() public async Task ManualSavingDuringAsyncQueryExecutionTest() { Require.ProviderIsNot(StorageProvider.Firebird, "Open reader reads lines that were inserted between getting reader and enumeratin it"); + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands. so having opened reader for query and making changes saved is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { _ = new TestEntity(session); @@ -562,6 +570,7 @@ public async Task ManualSavingDuringAsyncQueryExecutionFirebirdTest() [Test] public async Task ManualSavingDuringEnumerationTest() { + Require.ProviderIsNot(StorageProvider.PostgreSql, "No parallel executing for commands. so having opened reader for query and making changes saved is impossible"); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var readyToRockQuery = session.Query.All().AsAsync(); diff --git a/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs index b353272a95..1bb3485d1e 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs @@ -1,6 +1,6 @@ // Copyright (C) 2014-2021 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2014.04.14 @@ -850,6 +850,8 @@ public void ClientProfileSameExceptionWhenDoublePersist() [Test] public void ClientProfileSameExceptionWhenDoublePersistInsideTransaction() { + Require.ProviderIsNot(StorageProvider.PostgreSql, "UniqueVauleConstraint breaks the outermost transaction."); + using (var session = Domain.OpenSession(clientProfile)) { using (var transaction = session.OpenTransaction()) { var authorWithUniqueName = new Author {Name = "Peter"}; diff --git a/Orm/Xtensive.Orm.Tests/Storage/PostgreSqlSpatialTest.cs b/Orm/Xtensive.Orm.Tests/Storage/PostgreSqlSpatialTest.cs index c5bdd84b45..2227a7f4ea 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/PostgreSqlSpatialTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/PostgreSqlSpatialTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2014-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alena Mikshina // Created: 2014.04.09 @@ -67,7 +67,7 @@ public void MainTest() using (Domain.OpenSession()) { using (var t = Session.Current.OpenTransaction()) { - new Container { + _ = new Container { Point = new NpgsqlPoint(), LSeg = new NpgsqlLSeg(), Box = new NpgsqlBox(), @@ -76,7 +76,7 @@ public void MainTest() Circle = new NpgsqlCircle() }; - new Container { + _ = new Container { Point = point, LSeg = lSeg, Box = box, @@ -96,7 +96,7 @@ public void MainTest() Assert.IsTrue(record.Point.Equals(new NpgsqlPoint())); Assert.IsTrue(record.LSeg.Equals(new NpgsqlLSeg())); Assert.IsTrue(record.Box.Equals(new NpgsqlBox())); - Assert.IsTrue(record.Path.Equals(new NpgsqlPath(new[] {new NpgsqlPoint()}) {Open = true})); + Assert.IsTrue(record.Path.Equals(new NpgsqlPath(new[] {new NpgsqlPoint()}))); Assert.IsTrue(record.Polygon.Equals(new NpgsqlPolygon(new[] {new NpgsqlPoint()}))); Assert.IsTrue(record.Circle.Equals(new NpgsqlCircle())); diff --git a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs index e3123a1d5d..e9c4338fe0 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/RoundingTest.cs @@ -23,11 +23,11 @@ public class RoundingTest : AutoBuildTest [Test] public void TruncateTest() { - Query.All().Select(x => new { Decimal = x.FDecimal, DecimalTruncate = Math.Truncate(x.FDecimal) }) + Query.All().Select(x => new { Decimal = x.d18_9, DecimalTruncate = Math.Truncate(x.d18_9) }) .GroupBy(x => x.DecimalTruncate) .ForEach(i => i.ForEach(x => AreEqual(Math.Truncate(x.Decimal), x.DecimalTruncate))); - Query.All().Select(x => new { Double = x.FDouble, DoubleTruncate = Math.Truncate(x.FDouble) }) + Query.All().Select(x => new { Double = x.FDouble, DoubleTruncate = Math.Truncate(x.FDouble) }) .GroupBy(x => x.DoubleTruncate) .ForEach(i => i.ForEach(x => AreEqual(Math.Truncate(x.Double), x.DoubleTruncate))); } @@ -35,12 +35,12 @@ public void TruncateTest() [Test] public void CeilTest() { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalCeiling = Math.Ceiling(x.FDecimal) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalCeiling = Math.Ceiling(x.d18_9) }) .GroupBy(x => x.DecimalCeiling) .ForEach(x => x.ForEach(i => AreEqual(Math.Ceiling(i.Decimal), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleCeiling = Math.Ceiling(x.FDouble) }) .GroupBy(x => x.DoubleCeiling) .ForEach(x => x.ForEach(i => AreEqual(Math.Ceiling(i.Double), x.Key))); @@ -49,12 +49,12 @@ public void CeilTest() [Test] public void FloorTest() { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalFloor = Math.Floor(x.FDecimal) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalFloor = Math.Floor(x.d18_9) }) .GroupBy(x => x.DecimalFloor) .ForEach(x => x.ForEach(i => AreEqual(Math.Floor(i.Decimal), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleFloor = Math.Floor(x.FDouble) }) .GroupBy(x => x.DoubleFloor) .ForEach(x => x.ForEach(i => AreEqual(Math.Floor(i.Double), x.Key))); @@ -63,12 +63,12 @@ public void FloorTest() [Test] public void RoundDefaultToZeroDigitsTest() { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double), x.Key))); @@ -79,39 +79,41 @@ public void RoundDefaultToNonZeroDigitsTest() { if (ExpectNotSupported()) { var ex = Assert.Throws(() => - Query.All().Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1) }) + Query.All().Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, 1) }) .GroupBy(x => x.DecimalRound).Run()); Assert.That(ex.InnerException, Is.InstanceOf()); Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); ex = Assert.Throws(() => - Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1) }) + Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1) }) .GroupBy(x => x.DoubleRound).Run()); Assert.That(ex.InnerException, Is.InstanceOf()); Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); } else { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, 1) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1), x.Key))); } + + } [Test] public void RoundToEvenToZeroDigitsTest() { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, MidpointRounding.ToEven) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, MidpointRounding.ToEven) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, MidpointRounding.ToEven), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, MidpointRounding.ToEven) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, MidpointRounding.ToEven), x.Key))); @@ -122,24 +124,24 @@ public void RoundToEvenToNonZeroDigitsTest() { if (ExpectNotSupported()) {// sqlite has no support for Power operation var ex = Assert.Throws(() => - Query.All().Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.ToEven) }) + Query.All().Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, 1, MidpointRounding.ToEven) }) .GroupBy(x => x.DecimalRound).Run()); Assert.That(ex.InnerException, Is.InstanceOf()); Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); ex = Assert.Throws(() => - Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.ToEven) }) + Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.ToEven) }) .GroupBy(x => x.DoubleRound).Run()); Assert.That(ex.InnerException, Is.InstanceOf()); Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); } else { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.ToEven) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, 1, MidpointRounding.ToEven) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1, MidpointRounding.ToEven), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.ToEven) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1, MidpointRounding.ToEven), x.Key))); @@ -149,12 +151,12 @@ public void RoundToEvenToNonZeroDigitsTest() [Test] public void RoundAwayFromZeroToZeroDigitsTest() { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, MidpointRounding.AwayFromZero) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, MidpointRounding.AwayFromZero), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, MidpointRounding.AwayFromZero), x.Key))); @@ -165,24 +167,24 @@ public void RoundAwayFromZeroToNonZeroDigitsTest() { if (ExpectNotSupported()) { var ex = Assert.Throws(() => - Query.All().Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.AwayFromZero) }) + Query.All().Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, 1, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DecimalRound).Run()); Assert.That(ex.InnerException, Is.InstanceOf()); Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); ex = Assert.Throws(() => - Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.AwayFromZero) }) + Query.All().Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DoubleRound).Run()); Assert.That(ex.InnerException, Is.InstanceOf()); Assert.That(ex.InnerException.Message.Contains("Power", StringComparison.Ordinal)); } else { - Query.All() - .Select(x => new { Decimal = x.FDecimal, DecimalRound = Math.Round(x.FDecimal, 1, MidpointRounding.AwayFromZero) }) + Query.All() + .Select(x => new { Decimal = x.d18_9, DecimalRound = Math.Round(x.d18_9, 1, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DecimalRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Decimal, 1, MidpointRounding.AwayFromZero), x.Key))); - Query.All() + Query.All() .Select(x => new { Double = x.FDouble, DoubleRound = Math.Round(x.FDouble, 1, MidpointRounding.AwayFromZero) }) .GroupBy(x => x.DoubleRound) .ForEach(x => x.ForEach(i => AreEqual(Math.Round(i.Double, 1, MidpointRounding.AwayFromZero), x.Key))); @@ -229,7 +231,9 @@ public override void TestFixtureSetUp() }; foreach (var value in testValues) { - _ = new X { FDouble = (double) value, FDecimal = value }; + _ = new DoubleContainer { FDouble = (double) value }; + _ = new DecimalContainer { d18_9 = value }; + //_ = new X { FDouble = (double) value, FDecimal = value }; } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs b/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs index fd870a8dbc..27fba9a5bb 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2008.09.19 @@ -239,6 +239,16 @@ public class DecimalContainer : Entity [Field(Precision = 18, Scale = 0)] public decimal d18_0 { get; set; } } + + [HierarchyRoot] + public class DoubleContainer : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field] + public double FDouble { get; set; } + } } namespace Xtensive.Orm.Tests.Storage From 5446d6021218e673dca4918b09e3294c2c87f0ce Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 8 Apr 2021 19:36:49 +0500 Subject: [PATCH 46/71] PgSQL connection: skip commit/rollback operations when TX is already completed This prevents cerain cases of "swollowing" original exception by the exception due to attempt to commit/rollback already completed transaction in 'finally' part --- .../Sql.Drivers.PostgreSql/Connection.cs | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/Orm/Xtensive.Orm.PostgreSql/Sql.Drivers.PostgreSql/Connection.cs b/Orm/Xtensive.Orm.PostgreSql/Sql.Drivers.PostgreSql/Connection.cs index 7ab6919789..2222dc6579 100644 --- a/Orm/Xtensive.Orm.PostgreSql/Sql.Drivers.PostgreSql/Connection.cs +++ b/Orm/Xtensive.Orm.PostgreSql/Sql.Drivers.PostgreSql/Connection.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2009-2020 Xtensive LLC. +// Copyright (C) 2009-2021 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 @@ -9,6 +9,7 @@ using System.Data; using System.Data.Common; using Xtensive.Orm; +using System; namespace Xtensive.Sql.Drivers.PostgreSql { @@ -45,6 +46,38 @@ public override void BeginTransaction(IsolationLevel isolationLevel) activeTransaction = underlyingConnection.BeginTransaction(SqlHelper.ReduceIsolationLevel(isolationLevel)); } + public override void Commit() + { + EnsureIsNotDisposed(); + EnsureTransactionIsActive(); + + try { + if (!IsTransactionCompleted()) { + ActiveTransaction.Commit(); + } + } + finally { + ActiveTransaction.Dispose(); + ClearActiveTransaction(); + } + } + + public override void Rollback() + { + EnsureIsNotDisposed(); + EnsureTransactionIsActive(); + + try { + if (!IsTransactionCompleted()) { + ActiveTransaction.Rollback(); + } + } + finally { + ActiveTransaction.Dispose(); + ClearActiveTransaction(); + } + } + /// public override void MakeSavepoint(string name) { @@ -90,9 +123,14 @@ protected override void ClearUnderlyingConnection() underlyingConnection = null; } + private bool IsTransactionCompleted() + { + return activeTransaction != null && activeTransaction.IsCompleted; + } + // Constructors - [SecuritySafeCritical] + [SecuritySafeCritical] public Connection(SqlDriver driver) : base(driver) { From 4ed0c37e1bb4be3d1adc066d7b2e4472052fd47e Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 9 Apr 2021 18:04:48 +0500 Subject: [PATCH 47/71] PrefetchTest: Exclude PostgreSQL from test storages for PrefetchSingleTest + formatting update --- .../Storage/Prefetch/PrefetchTest.cs | 220 +++++++++--------- 1 file changed, 105 insertions(+), 115 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/Prefetch/PrefetchTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Prefetch/PrefetchTest.cs index 32f5c71624..cadf84740b 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Prefetch/PrefetchTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Prefetch/PrefetchTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexander Nikolaev // Created: 2009.09.30 @@ -28,7 +28,7 @@ protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); config.NamingConvention.NamespacePolicy = NamespacePolicy.AsIs; - config.Types.Register(typeof (Model.Offer).Assembly, typeof (Model.Offer).Namespace); + config.Types.Register(typeof(Model.Offer).Assembly, typeof(Model.Offer).Namespace); return config; } @@ -54,12 +54,10 @@ public void PrefetchGraphTest() .Prefetch(id => id.Track.Bytes)); var result = invoices.ToList(); foreach (var invoice in result) { - Console.Out.WriteLine(string.Format("Invoice: {0}, Customer: {1}, City {2}, Items count: {3}", invoice.InvoiceId, invoice.Customer.CompanyName, invoice.Customer.Address.City, invoice.InvoiceLines.Count)); - foreach (var orderDetail in invoice.InvoiceLines) - Console.Out.WriteLine(string.Format("\tTrack: {0}, Album: {1}, Track Length: {2}", - orderDetail.Track.Name, - orderDetail.Track.Album.Title, - orderDetail.Track.Bytes.Length)); + Console.WriteLine($"Invoice: {invoice.InvoiceId}, Customer CompanyName: {invoice.Customer.CompanyName}, City {invoice.Customer.Address.City}, Items count: {invoice.InvoiceLines.Count}"); + foreach (var orderDetail in invoice.InvoiceLines) { + Console.WriteLine($"\tTrack: {orderDetail.Track.Name}, Album: {orderDetail.Track.Album.Title}, Track Length: {orderDetail.Track.Bytes.Length}"); + } } t.Complete(); } @@ -79,12 +77,10 @@ public async Task PrefetchGraphAsyncTest() .Prefetch(id => id.Track.Bytes)).AsAsync(); var result = (await invoices).ToList(); foreach (var invoice in result) { - Console.Out.WriteLine(string.Format("Invoice: {0}, Customer: {1}, City {2}, Items count: {3}", invoice.InvoiceId, invoice.Customer.CompanyName, invoice.Customer.Address.City, invoice.InvoiceLines.Count)); - foreach (var orderDetail in invoice.InvoiceLines) - Console.Out.WriteLine(string.Format("\tTrack: {0}, Album: {1}, Track Length: {2}", - orderDetail.Track.Name, - orderDetail.Track.Album.Title, - orderDetail.Track.Bytes.Length)); + Console.Out.WriteLine($"Invoice: {invoice.InvoiceId}, Customer CompanyName: {invoice.Customer.CompanyName}, City {invoice.Customer.Address.City}, Items count: {invoice.InvoiceLines.Count}"); + foreach (var orderDetail in invoice.InvoiceLines) { + Console.WriteLine($"\tTrack: {orderDetail.Track.Name}, Album: {orderDetail.Track.Album.Title}, Track Length: {orderDetail.Track.Bytes.Length}"); + } } t.Complete(); } @@ -204,20 +200,24 @@ public void EnumerableOfNonEntityTest() using (var tx = session.OpenTransaction()) { var invoices = session.Query.Many(keys) .Prefetch(o => o.DesignatedEmployee); - var orderType = Domain.Model.Types[typeof (Invoice)]; - var employeeField = orderType.Fields["DesignatedEmployee"]; - var employeeType = Domain.Model.Types[typeof (Employee)]; - Func fieldSelector = field => field.IsPrimaryKey || field.IsSystem - || !field.IsLazyLoad && !field.IsEntitySet; + var orderType = Domain.Model.Types[typeof(Invoice)]; + var employeeField = orderType.Fields[nameof(Invoice.DesignatedEmployee)]; + var employeeType = Domain.Model.Types[typeof(Employee)]; + foreach (var invoice in invoices) { PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded(invoice.Key, invoice.Key.TypeInfo, session, fieldSelector); var invoiceState = session.EntityStateCache[invoice.Key, true]; - var employeeKey = Key.Create(Domain, WellKnown.DefaultNodeId, Domain.Model.Types[typeof (Employee)], + var employeeKey = Key.Create(Domain, WellKnown.DefaultNodeId, Domain.Model.Types[typeof(Employee)], TypeReferenceAccuracy.ExactType, employeeField.Associations.Last() .ExtractForeignKey(invoiceState.Type, invoiceState.Tuple)); PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded(employeeKey, employeeType, session, fieldSelector); } } + + static bool fieldSelector(FieldInfo field) + { + return field.IsPrimaryKey || field.IsSystem || !field.IsLazyLoad && !field.IsEntitySet; + } } [Test] @@ -234,11 +234,10 @@ public async Task EnumerableOfNonEntityAsyncTest() using (var tx = session.OpenTransaction()) { var invoices = session.Query.Many(keys) .Prefetch(o => o.DesignatedEmployee).AsAsync(); - var orderType = Domain.Model.Types[typeof (Invoice)]; - var employeeField = orderType.Fields["DesignatedEmployee"]; - var employeeType = Domain.Model.Types[typeof (Employee)]; - Func fieldSelector = field => field.IsPrimaryKey || field.IsSystem - || !field.IsLazyLoad && !field.IsEntitySet; + var invoiceType = Domain.Model.Types[typeof(Invoice)]; + var employeeField = invoiceType.Fields[nameof(Invoice.DesignatedEmployee)]; + var employeeType = Domain.Model.Types[typeof(Employee)]; + foreach (var invoice in await invoices) { PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded(invoice.Key, invoice.Key.TypeInfo, session, fieldSelector); var invoiceState = session.EntityStateCache[invoice.Key, true]; @@ -248,6 +247,11 @@ public async Task EnumerableOfNonEntityAsyncTest() PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded(employeeKey, employeeType, session, fieldSelector); } } + + static bool fieldSelector(FieldInfo field) + { + return field.IsPrimaryKey || field.IsSystem || !field.IsLazyLoad && !field.IsEntitySet; + } } [Test] @@ -258,10 +262,9 @@ public void EnumerableOfEntityTest() var prefetcher = session.Query.All() .Prefetch(o => o.ProcessingTime) .Prefetch(o => o.InvoiceLines); - var invoiceLineField = Domain.Model.Types[typeof (Invoice)].Fields["InvoiceLines"]; + var invoiceLineField = Domain.Model.Types[typeof(Invoice)].Fields[nameof(Invoice.InvoiceLines)]; foreach (var invoice in prefetcher) { - EntitySetState entitySetState; - Assert.IsTrue(session.Handler.LookupState(invoice.Key, invoiceLineField, out entitySetState)); + Assert.IsTrue(session.Handler.LookupState(invoice.Key, invoiceLineField, out var entitySetState)); Assert.IsTrue(entitySetState.IsFullyLoaded); } } @@ -275,10 +278,9 @@ public async Task EnumerableOfEntityAsyncTest() var prefetcher = session.Query.All() .Prefetch(o => o.ProcessingTime) .Prefetch(o => o.InvoiceLines).AsAsync(); - var invoiceLineField = Domain.Model.Types[typeof (Invoice)].Fields["InvoiceLines"]; + var invoiceLineField = Domain.Model.Types[typeof(Invoice)].Fields[nameof(Invoice.InvoiceLines)]; foreach (var invoice in await prefetcher) { - EntitySetState entitySetState; - Assert.IsTrue(session.Handler.LookupState(invoice.Key, invoiceLineField, out entitySetState)); + Assert.IsTrue(session.Handler.LookupState(invoice.Key, invoiceLineField, out var entitySetState)); Assert.IsTrue(entitySetState.IsFullyLoaded); } } @@ -325,7 +327,7 @@ public void PrefetchManyNotFullBatchTest() var entitySetState = GetFullyLoadedEntitySet(session, track.Key, invoicesField); foreach (var invoice in entitySetState) { count2++; - GetFullyLoadedEntitySet(session, invoice, invoiceLinesField); + _ = GetFullyLoadedEntitySet(session, invoice, invoiceLinesField); } } Console.WriteLine(count1); @@ -351,7 +353,7 @@ public async Task PrefetchManyNotFullBatchAsyncTest() var entitySetState = GetFullyLoadedEntitySet(session, track.Key, invoicesField); foreach (var invoice in entitySetState) { count2++; - GetFullyLoadedEntitySet(session, invoice, invoiceLinesField); + _ = GetFullyLoadedEntitySet(session, invoice, invoiceLinesField); } } Console.WriteLine(count1); @@ -365,8 +367,8 @@ public void PrefetchManySeveralBatchesTest() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - var linesField = Domain.Model.Types[typeof (Invoice)].Fields["InvoiceLines"]; - var trackField = Domain.Model.Types[typeof (InvoiceLine)].Fields["Track"]; + var linesField = Domain.Model.Types[typeof(Invoice)].Fields[nameof(Invoice.InvoiceLines)]; + var trackField = Domain.Model.Types[typeof(InvoiceLine)].Fields[nameof(InvoiceLine.Track)]; var invoices = session.Query.All() .Take(90) .Prefetch(o => o.InvoiceLines.Prefetch(od => od.Track)); @@ -392,8 +394,8 @@ public async Task PrefetchManySeveralBatchesAsyncTest() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - var linesField = Domain.Model.Types[typeof (Invoice)].Fields["InvoiceLines"]; - var trackField = Domain.Model.Types[typeof (InvoiceLine)].Fields["Track"]; + var linesField = Domain.Model.Types[typeof(Invoice)].Fields[nameof(Invoice.InvoiceLines)]; + var trackField = Domain.Model.Types[typeof(InvoiceLine)].Fields[nameof(InvoiceLine.Track)]; var invoices = session.Query.All() .Take(90) .Prefetch(o => o.InvoiceLines.Prefetch(od => od.Track)).AsAsync(); @@ -417,18 +419,19 @@ public async Task PrefetchManySeveralBatchesAsyncTest() [Test] public void PrefetchSingleTest() { - Require.ProviderIsNot(StorageProvider.Firebird); + Require.ProviderIsNot(StorageProvider.Firebird | StorageProvider.PostgreSql); List keys; using (var session = Domain.OpenSession()) - using (var tx = session.OpenTransaction()) + using (var tx = session.OpenTransaction()) { keys = session.Query.All().Select(o => o.Key).ToList(); + } using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - var invoiceType = Domain.Model.Types[typeof (Invoice)]; - var employeeType = Domain.Model.Types[typeof (Employee)]; - var employeeField = Domain.Model.Types[typeof (Invoice)].Fields["DesignatedEmployee"]; - var invoicesField = Domain.Model.Types[typeof (Employee)].Fields["Invoices"]; + var invoiceType = Domain.Model.Types[typeof(Invoice)]; + var employeeType = Domain.Model.Types[typeof(Employee)]; + var employeeField = Domain.Model.Types[typeof(Invoice)].Fields[nameof(Invoice.DesignatedEmployee)]; + var invoicesField = Domain.Model.Types[typeof(Employee)].Fields[nameof(Employee.Invoices)]; var invoices = session.Query.Many(keys) .Prefetch(o => o.DesignatedEmployee.Invoices); var count = 0; @@ -436,7 +439,7 @@ public void PrefetchSingleTest() Assert.AreEqual(keys[count], invoice.Key); count++; PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded(invoice.Key, invoiceType, session, - field => PrefetchHelper.IsFieldToBeLoadedByDefault(field) || field.Equals(employeeField) || (field.Parent!=null && field.Parent.Equals(employeeField))); + field => PrefetchHelper.IsFieldToBeLoadedByDefault(field) || field.Equals(employeeField) || (field.Parent != null && field.Parent.Equals(employeeField))); var state = session.EntityStateCache[invoice.Key, true]; PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded( state.Entity.GetFieldValue(employeeField).Key, @@ -451,18 +454,19 @@ public void PrefetchSingleTest() [Test] public async Task PrefetchSingleAsyncTest() { - Require.ProviderIsNot(StorageProvider.Firebird); + Require.ProviderIsNot(StorageProvider.Firebird | StorageProvider.PostgreSql); List keys; using (var session = Domain.OpenSession()) - using (var tx = session.OpenTransaction()) + using (var tx = session.OpenTransaction()) { keys = session.Query.All().Select(o => o.Key).ToList(); + } using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - var invoiceType = Domain.Model.Types[typeof (Invoice)]; - var employeeType = Domain.Model.Types[typeof (Employee)]; - var employeeField = Domain.Model.Types[typeof (Invoice)].Fields["DesignatedEmployee"]; - var invoicesField = Domain.Model.Types[typeof (Employee)].Fields["Invoices"]; + var invoiceType = Domain.Model.Types[typeof(Invoice)]; + var employeeType = Domain.Model.Types[typeof(Employee)]; + var employeeField = Domain.Model.Types[typeof(Invoice)].Fields[nameof(Invoice.DesignatedEmployee)]; + var invoicesField = Domain.Model.Types[typeof(Employee)].Fields[nameof(Employee.Invoices)]; var invoices = session.Query.Many(keys) .Prefetch(o => o.DesignatedEmployee.Invoices).AsAsync(); var count = 0; @@ -470,7 +474,7 @@ public async Task PrefetchSingleAsyncTest() Assert.AreEqual(keys[count], invoice.Key); count++; PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded(invoice.Key, invoiceType, session, - field => PrefetchHelper.IsFieldToBeLoadedByDefault(field) || field.Equals(employeeField) || (field.Parent!=null && field.Parent.Equals(employeeField))); + field => PrefetchHelper.IsFieldToBeLoadedByDefault(field) || field.Equals(employeeField) || (field.Parent != null && field.Parent.Equals(employeeField))); var state = session.EntityStateCache[invoice.Key, true]; PrefetchTestHelper.AssertOnlySpecifiedColumnsAreLoaded( state.Entity.GetFieldValue(employeeField).Key, @@ -619,7 +623,7 @@ public async Task ArgumentsAsyncTest() var b = (await session.Query.All() .Prefetch(t => t.Album.Title).AsAsync()) .ToList(); - Assert.ThrowsAsync(async () => (await session.Query.All() + _ = Assert.ThrowsAsync(async () => (await session.Query.All() .Prefetch(t => t.PersistenceState).AsAsync()) .ToList()); var d = (await session.Query.Many(EnumerableUtils.One(Key.Create(Domain, 1))) @@ -636,13 +640,14 @@ public void SimultaneouslyUsageOfMultipleEnumeratorsTest() var source = session.Query.All().ToList(); var prefetcher = source.Prefetch(i => i.InvoiceLines); using (var enumerator0 = prefetcher.GetEnumerator()) { - enumerator0.MoveNext(); - enumerator0.MoveNext(); - enumerator0.MoveNext(); + _ = enumerator0.MoveNext(); + _ = enumerator0.MoveNext(); + _ = enumerator0.MoveNext(); Assert.IsTrue(source.SequenceEqual(prefetcher)); var index = 3; - while (enumerator0.MoveNext()) + while (enumerator0.MoveNext()) { Assert.AreSame(source[index++], enumerator0.Current); + } Assert.AreEqual(source.Count, index); } } @@ -656,13 +661,14 @@ public async Task SimultaneouslyUsageOfMultipleEnumeratorsAsyncTest() var source = session.Query.All().ToList(); var prefetcher = await source.Prefetch(i => i.InvoiceLines).AsAsync(); using (var enumerator0 = prefetcher.GetEnumerator()) { - enumerator0.MoveNext(); - enumerator0.MoveNext(); - enumerator0.MoveNext(); + _ = enumerator0.MoveNext(); + _ = enumerator0.MoveNext(); + _ = enumerator0.MoveNext(); Assert.IsTrue(source.SequenceEqual(prefetcher)); var index = 3; - while (enumerator0.MoveNext()) + while (enumerator0.MoveNext()) { Assert.AreSame(source[index++], enumerator0.Current); + } Assert.AreEqual(source.Count, index); } } @@ -674,14 +680,14 @@ public void RootElementIsNullPrefetchTest() RemoveAllBooks(); using (var session = Domain.OpenSession()) { using (var tx = session.OpenTransaction()) { - new Model.Book {Title = new Model.Title {Text = "T0"}, Category = "1"}; + _ = new Model.Book { Title = new Model.Title { Text = "T0" }, Category = "1" }; tx.Complete(); } using (var tx = session.OpenTransaction()) { var books = session.Query.All().AsEnumerable() .Concat(EnumerableUtils.One(null)).Prefetch(b => b.Title); - var titleField = Domain.Model.Types[typeof (Model.Book)].Fields["Title"]; - var titleType = Domain.Model.Types[typeof (Model.Title)]; + var titleField = Domain.Model.Types[typeof(Model.Book)].Fields[nameof(Model.Book.Title)]; + var titleType = Domain.Model.Types[typeof(Model.Title)]; var count = 0; foreach (var book in books) { count++; @@ -701,18 +707,18 @@ public async Task RootElementIsNullPrefetchAsyncTest() RemoveAllBooks(); using (var session = Domain.OpenSession()) { using (var tx = session.OpenTransaction()) { - new Model.Book {Title = new Model.Title {Text = "T0"}, Category = "1"}; + _ = new Model.Book { Title = new Model.Title { Text = "T0" }, Category = "1" }; tx.Complete(); } using (var tx = session.OpenTransaction()) { var books = session.Query.All().AsEnumerable() .Concat(EnumerableUtils.One(null)).Prefetch(b => b.Title).AsAsync(); - var titleField = Domain.Model.Types[typeof(Model.Book)].Fields["Title"]; + var titleField = Domain.Model.Types[typeof(Model.Book)].Fields[nameof(Model.Book.Title)]; var titleType = Domain.Model.Types[typeof(Model.Title)]; var count = 0; foreach (var book in await books) { count++; - if (book!=null) { + if (book != null) { var titleKey = book.GetReferenceKey(titleField); PrefetchTestHelper.AssertOnlyDefaultColumnsAreLoaded(titleKey, titleType, session); } @@ -728,19 +734,20 @@ public void NestedPrefetchWhenChildElementIsNullTest() RemoveAllBooks(); using (var session = Domain.OpenSession()) { using (var tx = session.OpenTransaction()) { - var book0 = new Model.Book {Title = new Model.Title {Text = "T0"}, Category = "1"}; - var book1 = new Model.Book {Category = "2"}; + _ = new Model.Book { Title = new Model.Title { Text = "T0" }, Category = "1" }; + _ = new Model.Book { Category = "2" }; tx.Complete(); } using (var tx = session.OpenTransaction()) { var prefetcher = session.Query.All() .Prefetch(b => b.Title.Book); - var titleField = Domain.Model.Types[typeof (Model.Book)].Fields["Title"]; - var titleType = Domain.Model.Types[typeof (Model.Title)]; + var titleField = Domain.Model.Types[typeof(Model.Book)].Fields[nameof(Model.Book.Title)]; + var titleType = Domain.Model.Types[typeof(Model.Title)]; foreach (var book in prefetcher) { var titleKey = book.GetReferenceKey(titleField); - if (titleKey != null) + if (titleKey != null) { PrefetchTestHelper.AssertOnlyDefaultColumnsAreLoaded(titleKey, titleType, session); + } } } } @@ -752,19 +759,20 @@ public async Task NestedPrefetchWhenChildElementIsNullAsyncTest() RemoveAllBooks(); using (var session = Domain.OpenSession()) { using (var tx = session.OpenTransaction()) { - var book0 = new Model.Book {Title = new Model.Title {Text = "T0"}, Category = "1"}; - var book1 = new Model.Book {Category = "2"}; + _ = new Model.Book { Title = new Model.Title { Text = "T0" }, Category = "1" }; + _ = new Model.Book { Category = "2" }; tx.Complete(); } using (var tx = session.OpenTransaction()) { var prefetcher = session.Query.All() .Prefetch(b => b.Title.Book).AsAsync(); - var titleField = Domain.Model.Types[typeof(Model.Book)].Fields["Title"]; + var titleField = Domain.Model.Types[typeof(Model.Book)].Fields[nameof(Model.Book.Title)]; var titleType = Domain.Model.Types[typeof(Model.Title)]; foreach (var book in await prefetcher) { var titleKey = book.GetReferenceKey(titleField); - if (titleKey != null) + if (titleKey != null) { PrefetchTestHelper.AssertOnlyDefaultColumnsAreLoaded(titleKey, titleType, session); + } } } } @@ -776,7 +784,7 @@ public void NestedPrefetchWhenRootElementIsNullTest() RemoveAllBooks(); using (var session = Domain.OpenSession()) { using (var tx = session.OpenTransaction()) { - var book = new Model.Book {Title = new Model.Title {Text = "T0"}, Category = "1"}; + _ = new Model.Book { Title = new Model.Title { Text = "T0" }, Category = "1" }; tx.Complete(); } using (var tx = session.OpenTransaction()) { @@ -787,10 +795,11 @@ public void NestedPrefetchWhenRootElementIsNullTest() var count = 0; foreach (var book in books) { count++; - if (book!=null) { + if (book != null) { var titleKey = book.GetReferenceKey(titleField); - if (titleKey != null) + if (titleKey != null) { PrefetchTestHelper.AssertOnlyDefaultColumnsAreLoaded(titleKey, titleType, session); + } } } Assert.AreEqual(2, count); @@ -804,21 +813,22 @@ public async Task NestedPrefetchWhenRootElementIsNullAsyncTest() RemoveAllBooks(); using (var session = Domain.OpenSession()) { using (var tx = session.OpenTransaction()) { - var book = new Model.Book {Title = new Model.Title {Text = "T0"}, Category = "1"}; + _ = new Model.Book { Title = new Model.Title { Text = "T0" }, Category = "1" }; tx.Complete(); } using (var tx = session.OpenTransaction()) { var books = session.Query.All().AsEnumerable().Concat(EnumerableUtils.One(null)) .Prefetch(b => b.Title.Book).AsAsync(); - var titleField = Domain.Model.Types[typeof(Model.Book)].Fields["Title"]; + var titleField = Domain.Model.Types[typeof(Model.Book)].Fields[nameof(Model.Book.Title)]; var titleType = Domain.Model.Types[typeof(Model.Title)]; var count = 0; foreach (var book in await books) { count++; - if (book!=null) { + if (book != null) { var titleKey = book.GetReferenceKey(titleField); - if (titleKey!=null) + if (titleKey != null) { PrefetchTestHelper.AssertOnlyDefaultColumnsAreLoaded(titleKey, titleType, session); + } } } Assert.AreEqual(2, count); @@ -829,13 +839,8 @@ public async Task NestedPrefetchWhenRootElementIsNullAsyncTest() [Test] public void StructureFieldsPrefetchTest() { - Key containerKey; - Key bookShop0Key; - Key book0Key; - Key bookShop1Key; - Key book1Key; - PrefetchTestHelper.CreateOfferContainer(Domain, out containerKey, out book0Key, out bookShop0Key, - out book1Key, out bookShop1Key); + PrefetchTestHelper.CreateOfferContainer(Domain, out var containerKey, out var book0Key, + out var bookShop0Key, out var book1Key, out var bookShop1Key); using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { @@ -852,13 +857,8 @@ public void StructureFieldsPrefetchTest() [Test] public async Task StructureFieldsPrefetchAsyncTest() { - Key containerKey; - Key bookShop0Key; - Key book0Key; - Key bookShop1Key; - Key book1Key; - PrefetchTestHelper.CreateOfferContainer(Domain, out containerKey, out book0Key, out bookShop0Key, - out book1Key, out bookShop1Key); + PrefetchTestHelper.CreateOfferContainer(Domain, out var containerKey, out var book0Key, + out var bookShop0Key, out var book1Key, out var bookShop1Key); using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { @@ -875,13 +875,8 @@ public async Task StructureFieldsPrefetchAsyncTest() [Test] public void StructurePrefetchTest() { - Key containerKey; - Key bookShop0Key; - Key book0Key; - Key bookShop1Key; - Key book1Key; - PrefetchTestHelper.CreateOfferContainer(Domain, out containerKey, out book0Key, out bookShop0Key, - out book1Key, out bookShop1Key); + PrefetchTestHelper.CreateOfferContainer(Domain, out var containerKey, out var book0Key, + out var bookShop0Key, out var book1Key, out var bookShop1Key); using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { @@ -897,13 +892,8 @@ public void StructurePrefetchTest() [Test] public async Task StructurePefetchAsyncTest() { - Key containerKey; - Key bookShop0Key; - Key book0Key; - Key bookShop1Key; - Key book1Key; - PrefetchTestHelper.CreateOfferContainer(Domain, out containerKey, out book0Key, out bookShop0Key, - out book1Key, out bookShop1Key); + PrefetchTestHelper.CreateOfferContainer(Domain, out var containerKey, out var book0Key, + out var bookShop0Key, out var book1Key, out var bookShop1Key); using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { @@ -920,8 +910,9 @@ private void RemoveAllBooks() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - foreach (var book in session.Query.All()) + foreach (var book in session.Query.All()) { book.Remove(); + } tx.Complete(); } } @@ -929,8 +920,7 @@ private void RemoveAllBooks() private static EntitySetState GetFullyLoadedEntitySet(Session session, Key key, FieldInfo employeesField) { - EntitySetState entitySetState; - Assert.IsTrue(session.Handler.LookupState(key, employeesField, out entitySetState)); + Assert.IsTrue(session.Handler.LookupState(key, employeesField, out var entitySetState)); Assert.IsTrue(entitySetState.IsFullyLoaded); return entitySetState; } From b42f150a72d714c8c463a1405bbb56f371773853 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 28 Apr 2021 14:36:08 +0500 Subject: [PATCH 48/71] Unify test schemas --- .../Storage/Multimapping/MultischemaTest.cs | 10 +++++----- .../Storage/Multinode/SchemaMultinodeTest.cs | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs index 28fd0b3fdb..1c558c435f 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012 Xtensive LLC. +// Copyright (C) 2012-2021 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -12,10 +12,10 @@ namespace Xtensive.Orm.Tests.Storage.Multimapping { public abstract class MultischemaTest : MultimappingTest { - protected const string Schema1Name = "test1"; - protected const string Schema2Name = "test2"; - protected const string Schema3Name = "test3"; - protected const string Schema4Name = "test4"; + protected const string Schema1Name = "Model1"; + protected const string Schema2Name = "Model2"; + protected const string Schema3Name = "Model3"; + protected const string Schema4Name = "Model4"; protected override void CheckRequirements() { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs index 8e1737843e..d9fc1d72d7 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2014 Xtensive LLC. +// Copyright (C) 2014-2021 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -13,9 +13,9 @@ namespace Xtensive.Orm.Tests.Storage.Multinode [TestFixture] public class SchemaMultinodeTest : StandardMultinodeTest { - private const string DefaultSchema = "n1"; - private const string SecondSchema = "n2"; - private const string ThirdSchema = "n3"; + private const string DefaultSchema = "Model1"; + private const string SecondSchema = "Model2"; + private const string ThirdSchema = "Model3"; protected override void CheckRequirements() { From d3842056e1f96beef612eef93a5621a29a58945f Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 29 Apr 2021 12:30:43 +0500 Subject: [PATCH 49/71] Introduce WellKnownSchemas and WellKnownDatabases + some formatting update --- .../MultipleNodesTest.cs | 10 +- .../WellKnownDatabases.cs | 40 + .../WellKnownSchemas.cs | 34 + ...ueJira0537_DropDefaultConstraintBugTest.cs | 6 +- ...eMappingCachingInMaterializationContext.cs | 28 +- ...0647_StoredDomainModelMappingsUpdateBug.cs | 22 +- .../Storage/IgnoreRulesValidateTest.cs | 132 ++-- .../Storage/Multimapping/MultidatabaseTest.cs | 12 +- .../Storage/Multimapping/MultischemaTest.cs | 8 +- .../Multinode/ConnectionOverrideTest.cs | 21 +- .../InitializationSqlOverrideTest.cs | 40 +- .../ObsoleteSelectStorageNodeTest.cs | 8 +- .../Storage/Multinode/QueryCachingTest.cs | 12 +- .../Storage/Multinode/SchemaMultinodeTest.cs | 10 +- .../Multinode/StorageNodeManagerTest.cs | 33 +- .../Storage/Multinode/TypeIdAllocationTest.cs | 110 +-- .../MultidatabaseEntityManipulationTest.cs | 44 +- .../MultischemaEntityManipulationTest.cs | 31 +- .../KeyGenerator/MultidatabaseTest.cs | 36 +- .../KeyGenerator/MultischemaTest.cs | 25 +- .../Upgrade/BuildOnEmptySchemaTest.cs | 61 +- .../CustomTypeIdMap/CustomTypeIdMap.cs | 697 +++++++++--------- .../FullText/DynamicFullTextCatalogTest.cs | 225 +++--- .../GeneratorUpgrade/MultidatabaseTest.cs | 8 +- .../GeneratorUpgrade/MultischemaTest.cs | 6 +- .../GeneratorUpgrade/SimpleSchemaTest.cs | 4 +- .../HugeModelUpgrade/DatabasePerNodeTest.cs | 21 +- .../HugeModelUpgrade/MappedTypesNodesTest.cs | 21 +- .../HugeModelUpgrade/SchemaPerNodeTest.cs | 17 +- .../TwoDatabasesPerNodeTest.cs | 29 +- .../HugeModelUpgrade/TwoSchemasPerNodeTest.cs | 22 +- .../NewSkip/MultidatabaseDomainTest.cs | 115 +-- .../Upgrade/NewSkip/MultischemaDomainTest.cs | 109 +-- .../Upgrade/NewSkip/SingleDatabaseNodeTest.cs | 10 +- .../NewSkip/SingleSchemaNodeBuildingTest.cs | 10 +- .../NodeBasedExtractedModelBuilderTest.cs | 434 +++++------ .../Upgrade/SchemaSharing/IgnoreRulesTest.cs | 7 +- .../SchemaSharing/MappingResolverTest.cs | 269 +++---- .../MetadataUpdate/MultidatabaseTest.cs | 53 +- .../MetadataUpdate/MultischemaTest.cs | 40 +- .../SchemaSharing/QueryBuilder/Model.cs | 133 ++-- .../QueryBuilder/MultidatabaseTest.cs | 40 +- .../QueryBuilder/MultischemaTest.cs | 29 +- .../Requests/MultidatabaseTest.cs | 40 +- .../SchemaSharing/Requests/MultischemaTest.cs | 29 +- .../SchemaSharing/SqlExecutor/Model.cs | 133 ++-- .../SqlExecutor/MultidatabaseTest.cs | 40 +- .../SqlExecutor/MultischemaTest.cs | 25 +- .../SchemaSharing/StorageNodeBuildingTest.cs | 7 +- .../MultidatabaseTest.cs | 31 +- .../TemporaryTableManager/MultischemaTest.cs | 31 +- .../Upgrade/UpgradeContextTest.cs | 90 ++- 52 files changed, 1870 insertions(+), 1578 deletions(-) create mode 100644 Orm/Xtensive.Orm.Tests.Framework/WellKnownDatabases.cs create mode 100644 Orm/Xtensive.Orm.Tests.Framework/WellKnownSchemas.cs diff --git a/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs b/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs index ed999a177f..a5096e4b28 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/MultipleNodesTest.cs @@ -21,11 +21,11 @@ public class MultipleNodesTest : CommonModelTest private const string Node3Id = "Node3"; private const string Node4Id = "Node4"; - private const string DefaultNodeSchema = "dbo"; - private const string FirstNodeSchema = "Model1"; - private const string SecondNodeSchema = "Model2"; - private const string ThridNodeSchema = "Model3"; - private const string ForthNodeSchema = "Model4"; + private const string DefaultNodeSchema = WellKnownSchemas.Schema1; + private const string FirstNodeSchema = WellKnownSchemas.Schema2; + private const string SecondNodeSchema = WellKnownSchemas.Schema3; + private const string ThridNodeSchema = WellKnownSchemas.Schema4; + private const string ForthNodeSchema = WellKnownSchemas.Schema5; private static readonly CultureInfo EnglishCulture = new CultureInfo("en-US"); private static readonly string EnglishTitle = "Welcome!"; diff --git a/Orm/Xtensive.Orm.Tests.Framework/WellKnownDatabases.cs b/Orm/Xtensive.Orm.Tests.Framework/WellKnownDatabases.cs new file mode 100644 index 0000000000..b08ff63036 --- /dev/null +++ b/Orm/Xtensive.Orm.Tests.Framework/WellKnownDatabases.cs @@ -0,0 +1,40 @@ +// Copyright (C) 2021 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.Text; + +namespace Xtensive.Orm.Tests +{ + /// + /// Well-known databases which are used in tests + /// + public static class WellKnownDatabases + { + public const string SqlServerMasterDb = "master"; + + /// + /// Can be used in multi-database tests. + /// + public static class MultiDatabase + { + public const string MainDb = "DO-Tests"; + + // Additional databases which can be used for multi-database tests + public const string AdditionalDb1 = "DO-Tests-1"; + public const string AdditionalDb2 = "DO-Tests-2"; + public const string AdditionalDb3 = "DO-Tests-3"; + public const string AdditionalDb4 = "DO-Tests-4"; + public const string AdditionalDb5 = "DO-Tests-5"; + public const string AdditionalDb6 = "DO-Tests-6"; + public const string AdditionalDb7 = "DO-Tests-7"; + public const string AdditionalDb8 = "DO-Tests-8"; + public const string AdditionalDb9 = "DO-Tests-9"; + public const string AdditionalDb10 = "DO-Tests-10"; + public const string AdditionalDb11 = "DO-Tests-11"; + public const string AdditionalDb12 = "DO-Tests-12"; + } + } +} diff --git a/Orm/Xtensive.Orm.Tests.Framework/WellKnownSchemas.cs b/Orm/Xtensive.Orm.Tests.Framework/WellKnownSchemas.cs new file mode 100644 index 0000000000..b9468cd599 --- /dev/null +++ b/Orm/Xtensive.Orm.Tests.Framework/WellKnownSchemas.cs @@ -0,0 +1,34 @@ +// Copyright (C) 2021 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.Text; + +namespace Xtensive.Orm.Tests +{ + /// + /// Well-known schemas which are used in tests + /// + public static class WellKnownSchemas + { + // storage-specific schemas + public const string SqlServerDefaultSchema = "dbo"; + public const string PgSqlDefalutSchema = "public"; + + // general purpose schemas + public const string Schema1 = "Model1"; + public const string Schema2 = "Model2"; + public const string Schema3 = "Model3"; + public const string Schema4 = "Model4"; + public const string Schema5 = "Model5"; + public const string Schema6 = "Model6"; + public const string Schema7 = "Model7"; + public const string Schema8 = "Model8"; + public const string Schema9 = "Model9"; + public const string Schema10 = "Model10"; + public const string Schema11 = "Model11"; + public const string Schema12 = "Model12"; + } +} diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs index c5e8405dab..a8165ba33b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs @@ -274,11 +274,11 @@ namespace Xtensive.Orm.Tests.Issues [TestFixture] public class IssueJira0537_DropDefaultConstraintBugTest : AutoBuildTest { - private const string Database1Name = "DO-Tests-1"; - private const string Database2Name = "DO-Tests-2"; + private const string Database1Name = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string Database2Name = WellKnownDatabases.MultiDatabase.AdditionalDb1; private const string CoreAlias = "core"; private const string WmsAlias = "wms"; - private const string SpecialSchemaAlias = "dbo"; + private const string SpecialSchemaAlias = WellKnownSchemas.SqlServerDefaultSchema; private ConnectionInfo connectionInfo; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0614_TypeMappingCachingInMaterializationContext.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0614_TypeMappingCachingInMaterializationContext.cs index dbf337f241..f9b80f8cc0 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0614_TypeMappingCachingInMaterializationContext.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0614_TypeMappingCachingInMaterializationContext.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2015-2020 Xtensive LLC. +// Copyright (C) 2015-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -191,6 +191,9 @@ namespace Xtensive.Orm.Tests.Issues { public class IssueJira0614_MaterializationContextModel { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Node2Name = "Node2"; private const string Node1Name = "Node1"; @@ -200,8 +203,8 @@ public class IssueJira0614_MaterializationContextModel [Test] public void Test01() { - var configuration1 = CreateConfiguration(typeof(Node1.TimesheetCode), DomainUpgradeMode.Recreate, "Model1"); - var configuration2 = CreateConfiguration(typeof(Node2.TimesheetCode), DomainUpgradeMode.Recreate, "Model2"); + var configuration1 = CreateConfiguration(typeof(Node1.TimesheetCode), DomainUpgradeMode.Recreate, Schema1); + var configuration2 = CreateConfiguration(typeof(Node2.TimesheetCode), DomainUpgradeMode.Recreate, Schema2); using (var domain = BuildDomain(configuration1)) { Assert.That(domain.Model.Types[typeof(Node1.TimesheetCode)].TypeId, Is.EqualTo(288)); @@ -263,8 +266,8 @@ public void Test01() } } - var multinodeDomainConfiguration = CreateConfiguration(typeof(Target.TimesheetCode), DomainUpgradeMode.Skip, "Model1"); - var nodeConfiguration = CreateNodeConfiguration(Node2Name, "Model1", "Model2", DomainUpgradeMode.Skip); + var multinodeDomainConfiguration = CreateConfiguration(typeof(Target.TimesheetCode), DomainUpgradeMode.Skip, Schema1); + var nodeConfiguration = CreateNodeConfiguration(Node2Name, Schema1, Schema2, DomainUpgradeMode.Skip); using (var domain = BuildDomain(multinodeDomainConfiguration, nodeConfiguration)) { using (var session = domain.OpenSession()) { @@ -311,8 +314,8 @@ public void Test01() [Test] public void Test02() { - var configuration1 = CreateConfiguration(typeof(Node1.TimesheetCode), DomainUpgradeMode.Recreate, "Model1"); - var configuration2 = CreateConfiguration(typeof(Node2.TimesheetCode), DomainUpgradeMode.Recreate, "Model2"); + var configuration1 = CreateConfiguration(typeof(Node1.TimesheetCode), DomainUpgradeMode.Recreate, Schema1); + var configuration2 = CreateConfiguration(typeof(Node2.TimesheetCode), DomainUpgradeMode.Recreate, Schema2); using (var domain = BuildDomain(configuration1)) { Assert.That(domain.Model.Types[typeof(Node1.TimesheetCode)].TypeId, Is.EqualTo(288)); @@ -375,8 +378,8 @@ public void Test02() } } - var multinodeDomainConfiguration = CreateConfiguration(typeof(Target.TimesheetCode), DomainUpgradeMode.PerformSafely, "Model2"); - var nodeConfiguration = CreateNodeConfiguration(Node1Name, "Model2", "Model1", DomainUpgradeMode.PerformSafely); + var multinodeDomainConfiguration = CreateConfiguration(typeof(Target.TimesheetCode), DomainUpgradeMode.PerformSafely, Schema2); + var nodeConfiguration = CreateNodeConfiguration(Node1Name, Schema2, Schema1, DomainUpgradeMode.PerformSafely); using (var domain = BuildDomain(multinodeDomainConfiguration, nodeConfiguration)) { using (var session = domain.OpenSession()) { @@ -435,13 +438,14 @@ private Domain BuildDomain(DomainConfiguration configuration, NodeConfiguration { try{ var domain = Domain.Build(configuration); - if (nodeConfiguration!=null) - domain.StorageNodeManager.AddNode(nodeConfiguration); + if (nodeConfiguration != null) { + _ = domain.StorageNodeManager.AddNode(nodeConfiguration); + } return domain; } catch (Exception e) { TestLog.Error(GetType().GetFullName()); - TestLog.Error(e); + _ = TestLog.Error(e); throw; } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0647_StoredDomainModelMappingsUpdateBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0647_StoredDomainModelMappingsUpdateBug.cs index ececac6a07..800c0f59b6 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0647_StoredDomainModelMappingsUpdateBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0647_StoredDomainModelMappingsUpdateBug.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -381,6 +381,9 @@ private class ClientNodeConfiguration public string DefaultSchema { get; set; } } + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private ClientNodeConfiguration alpha; private ClientNodeConfiguration beta; private ClientNodeConfiguration main; @@ -542,27 +545,27 @@ private void BuildNodeConfigurationsMetadata() main = new ClientNodeConfiguration { Name = "main", ConnectionInfo = ComposeConnectionToMasterDatabase(defaultConnection), - InitializationSql = "USE [DO-Tests-1]", - DefaultSchema = "dbo" + InitializationSql = $"USE [{DOTests1Db}]", + DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema }; alpha = new ClientNodeConfiguration { Name = "alpha", ConnectionInfo = ComposeConnectionToMasterDatabase(defaultConnection), - InitializationSql = "USE [DO-Tests-1]", - DefaultSchema = "Model1" + InitializationSql = $"USE [{DOTests1Db}]", + DefaultSchema = WellKnownSchemas.Schema1 }; beta = new ClientNodeConfiguration { Name = "beta", ConnectionInfo = ComposeConnectionToMasterDatabase(defaultConnection), - InitializationSql = "USE [DO-Tests-2]", - DefaultSchema = "Model2" + InitializationSql = $"USE [{DOTests2Db}]", + DefaultSchema = WellKnownSchemas.Schema2 }; } private ConnectionInfo ComposeConnectionToMasterDatabase(ConnectionInfo baseConnectionInfo) { - if (baseConnectionInfo.ConnectionUrl==null) { + if (baseConnectionInfo.ConnectionUrl == null) { throw new InvalidOperationException("Can't convert connection string based ConnectionInfo"); } @@ -571,7 +574,6 @@ private ConnectionInfo ComposeConnectionToMasterDatabase(ConnectionInfo baseConn var password = baseConnectionInfo.ConnectionUrl.Password; var host = baseConnectionInfo.ConnectionUrl.Host; var port = baseConnectionInfo.ConnectionUrl.Port; - var database = "master"; var parameters = baseConnectionInfo.ConnectionUrl.Params; var urlTemplate = "{0}://{1}{2}{3}/{4}{5}"; @@ -592,7 +594,7 @@ private ConnectionInfo ComposeConnectionToMasterDatabase(ConnectionInfo baseConn parametersPart = parametersPart.TrimEnd('&'); } - var newUrl = string.Format(urlTemplate, provider, authentication, host, portPart, database, parametersPart); + var newUrl = string.Format(urlTemplate, provider, authentication, host, portPart, WellKnownDatabases.SqlServerMasterDb, parametersPart); return new ConnectionInfo(newUrl); } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs index b9a8dd1ada..3d95578fc1 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs @@ -264,6 +264,10 @@ namespace Xtensive.Orm.Tests.Storage [TestFixture] public class IgnoreRulesValidateTest { + private const string defaultSchema = WellKnownSchemas.Schema1; + private const string Schema1 = WellKnownSchemas.Schema2; + private const string Schema2 = WellKnownSchemas.Schema3; + private SqlDriver sqlDriver; private Key changedOrderKey; private bool createConstraintsWithTable; @@ -303,7 +307,7 @@ public void IgnoreSimpleColumnTest() { BuildSimpleDomain(DomainUpgradeMode.Recreate, null, typeof(Model3.MyEntity1)).Dispose(); - var catalog = GetCatalog(); + var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.Int32)); var ignoreRuleCollection = new IgnoreRuleCollection(); @@ -609,27 +613,27 @@ public void MultischemaValidateTest() SetMultischema(); var catalog = GetCatalog(); - CreateSchema(catalog, "Model1"); - CreateSchema(catalog, "Model2"); + CreateSchema(catalog, Schema1); + CreateSchema(catalog, Schema2); BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); catalog = GetCatalog(); - CreateColumn(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKeyInDb(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; - CreateTable(catalog, "Model2", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKeyInDb(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKeyInDb(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); + CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); var ignoreRules = new IgnoreRuleCollection(); - _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); - _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); - _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema(Schema1); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema(Schema1); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema(Schema1); BuildComplexDomain(DomainUpgradeMode.Validate, ignoreRules, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); } @@ -644,17 +648,17 @@ public void MultidatabaseValidateTest() BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); - CreateColumn(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); - CreateForeignKeyInDb(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); + CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); + CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; - CreateTable(secondCatalog, "dbo", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); - CreatePrimaryKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); - CreateForeignKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); + CreateTable(secondCatalog, defaultSchema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); + CreatePrimaryKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); + CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); var ignoreRules = new IgnoreRuleCollection(); - _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("dbo").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(defaultSchema).WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); _ = ignoreRules.IgnoreTable("IgnoredTable").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenDatabase(Multimapping.MultidatabaseTest.Database1Name); @@ -671,33 +675,33 @@ public void MultischemaUpgrageInPerformModeTest() SetMultischema(); var catalog = GetCatalog(); - CreateSchema(catalog, "Model1"); - CreateSchema(catalog, "Model2"); + CreateSchema(catalog, Schema1); + CreateSchema(catalog, Schema2); BuildDomainAndFillData(); catalog = GetCatalog(); - CreateColumn(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKeyInDb(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; - CreateTable(catalog, "Model2", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKeyInDb(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKeyInDb(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); + CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); var ignoreRules = new IgnoreRuleCollection(); - _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); - _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); - _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema(Schema1); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema(Schema1); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema(Schema1); UpgradeDomain(DomainUpgradeMode.Perform, ignoreRules); ignoreRules = new IgnoreRuleCollection(); - _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema(Schema2); BuildDomainInValidateMode(ignoreRules); - ValidateMyEntity(catalog, "Model2"); + ValidateMyEntity(catalog, Schema2); } [Test] @@ -708,33 +712,33 @@ public void MultischemaUpgrageInPerformSafelyModeTest() SetMultischema(); var catalog = GetCatalog(); - CreateSchema(catalog, "Model1"); - CreateSchema(catalog, "Model2"); + CreateSchema(catalog, Schema1); + CreateSchema(catalog, Schema2); BuildDomainAndFillData(); catalog = GetCatalog(); - CreateColumn(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); - CreateForeignKeyInDb(catalog, "Model2", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; - CreateTable(catalog, "Model2", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); - CreatePrimaryKeyInDb(catalog, "Model2", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKeyInDb(catalog, "Model2", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); + CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); + CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); var ignoreRules = new IgnoreRuleCollection(); - _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema("Model1"); - _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema("Model1"); - _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema("Model1"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("IgnoredTable").WhenSchema(Schema1); + _ = ignoreRules.IgnoreColumn("SomeIgnoredField").WhenTable("Order").WhenSchema(Schema1); + _ = ignoreRules.IgnoreColumn("IgnoredColumn.Id").WhenTable("Author").WhenSchema(Schema1); UpgradeDomain(DomainUpgradeMode.PerformSafely, ignoreRules); ignoreRules = new IgnoreRuleCollection(); - _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema("Model2"); - _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema("Model2"); + _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); + _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenSchema(Schema2); BuildDomainInValidateMode(ignoreRules); - ValidateMyEntity(catalog, "Model2"); + ValidateMyEntity(catalog, Schema2); } [Test] @@ -747,14 +751,14 @@ public void MultidatabaseUpgradeInPerformModeTest() BuildDomainAndFillData(); var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); - CreateColumn(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); - CreateForeignKeyInDb(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); + CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); + CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; - CreateTable(secondCatalog, "dbo", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); - CreatePrimaryKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); - CreateForeignKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); + CreateTable(secondCatalog, defaultSchema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); + CreatePrimaryKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); + CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); @@ -768,7 +772,7 @@ public void MultidatabaseUpgradeInPerformModeTest() _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); BuildDomainInValidateMode(ignoreRules); - ValidateMyEntity(secondCatalog, "dbo", true); + ValidateMyEntity(secondCatalog, defaultSchema, true); } [Test] @@ -780,13 +784,13 @@ public void MultidatabaseUpgradeInPerformSafelyModeTest() BuildDomainAndFillData(); var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); - CreateColumn(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); - CreateForeignKeyInDb(secondCatalog, "dbo", "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); + CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); + CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; - CreateTable(secondCatalog, "dbo", "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); - CreatePrimaryKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); - CreateForeignKeyInDb(secondCatalog, "dbo", "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); + CreateTable(secondCatalog, defaultSchema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); + CreatePrimaryKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); + CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); @@ -800,7 +804,7 @@ public void MultidatabaseUpgradeInPerformSafelyModeTest() _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); _ = ignoreRules.IgnoreTable("MyIgnoredEntity").WhenDatabase(Multimapping.MultidatabaseTest.Database2Name); BuildDomainInValidateMode(ignoreRules); - ValidateMyEntity(secondCatalog, "dbo", true); + ValidateMyEntity(secondCatalog, defaultSchema, true); } private Domain BuildSimpleDomain(DomainUpgradeMode mode, IgnoreRuleCollection ignoreRules, Type sourceType, params Type[] additionalSourceTypes) @@ -825,11 +829,11 @@ private Domain BuildComplexDomain(DomainUpgradeMode mode, IgnoreRuleCollection i config.UpgradeMode = mode; if (isMultischemaTest) { foreach (var type in firstPartTypes) { - config.MappingRules.Map(type.Assembly, type.Namespace).ToSchema("Model1"); + config.MappingRules.Map(type.Assembly, type.Namespace).ToSchema(Schema1); } foreach (var type in secondPartTypes) { - config.MappingRules.Map(type.Assembly, type.Namespace).ToSchema("Model2"); + config.MappingRules.Map(type.Assembly, type.Namespace).ToSchema(Schema2); } } else if (isMultidatabaseTest) { @@ -842,7 +846,7 @@ private Domain BuildComplexDomain(DomainUpgradeMode mode, IgnoreRuleCollection i } } - config.DefaultSchema = "dbo"; + config.DefaultSchema = defaultSchema; config.DefaultDatabase = GetConnectionInfo().ConnectionUrl.GetDatabase(); foreach (var type in firstPartTypes.Union(secondPartTypes)) { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultidatabaseTest.cs index 58f7eb66a9..3916064de3 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultidatabaseTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012 Xtensive LLC. +// Copyright (C) 2012-2021 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -11,12 +11,12 @@ namespace Xtensive.Orm.Tests.Storage.Multimapping { public abstract class MultidatabaseTest : MultimappingTest { - public const string DefaultSchemaName = "dbo"; + public const string DefaultSchemaName = WellKnownSchemas.SqlServerDefaultSchema; - public const string Database1Name = "DO-Tests-1"; - public const string Database2Name = "DO-Tests-2"; - public const string Database3Name = "DO-Tests-3"; - public const string Database4Name = "DO-Tests-4"; + public const string Database1Name = WellKnownDatabases.MultiDatabase.AdditionalDb1; + public const string Database2Name = WellKnownDatabases.MultiDatabase.AdditionalDb2; + public const string Database3Name = WellKnownDatabases.MultiDatabase.AdditionalDb3; + public const string Database4Name = WellKnownDatabases.MultiDatabase.AdditionalDb4; protected override DomainConfiguration BuildConfiguration() { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs index 1c558c435f..aadf26f05a 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/MultischemaTest.cs @@ -12,10 +12,10 @@ namespace Xtensive.Orm.Tests.Storage.Multimapping { public abstract class MultischemaTest : MultimappingTest { - protected const string Schema1Name = "Model1"; - protected const string Schema2Name = "Model2"; - protected const string Schema3Name = "Model3"; - protected const string Schema4Name = "Model4"; + protected const string Schema1Name = WellKnownSchemas.Schema1; + protected const string Schema2Name = WellKnownSchemas.Schema2; + protected const string Schema3Name = WellKnownSchemas.Schema3; + protected const string Schema4Name = WellKnownSchemas.Schema4; protected override void CheckRequirements() { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/ConnectionOverrideTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/ConnectionOverrideTest.cs index a918ef1afe..b6db1e359d 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/ConnectionOverrideTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/ConnectionOverrideTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2020 Xtensive LLC. +// Copyright (C) 2020-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -27,6 +27,9 @@ public TestEntity(Session session) } } + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + private const string Schema1 = WellKnownSchemas.Schema1; + [OneTimeSetUp] public void OneTimeSetUp() => Require.ProviderIs(StorageProvider.SqlServer); @@ -35,22 +38,22 @@ public void NullNodeConnectionTest() { var domainConfig = DomainConfigurationFactory.Create(); domainConfig.Types.Register(typeof(TestEntity)); - domainConfig.DefaultSchema = "dbo"; + domainConfig.DefaultSchema = dbo; domainConfig.UpgradeMode = DomainUpgradeMode.Recreate; var nodeConfig = new NodeConfiguration("Additional"); nodeConfig.UpgradeMode = DomainUpgradeMode.Recreate; nodeConfig.ConnectionInfo = null; - nodeConfig.SchemaMapping.Add("dbo", "Model1"); + nodeConfig.SchemaMapping.Add(dbo, Schema1); void commandValidator(object sender, DbCommandEventArgs args) { var session = ((SessionEventAccessor) sender).Session; if (session.StorageNodeId == WellKnown.DefaultNodeId) { - Assert.That(args.Command.CommandText.Contains("[dbo].[ConnectionOverrideTest.TestEntity]"), Is.True); + Assert.That(args.Command.CommandText.Contains($"[{dbo}].[ConnectionOverrideTest.TestEntity]"), Is.True); } else { - Assert.That(args.Command.CommandText.Contains("[Model1].[ConnectionOverrideTest.TestEntity]"), Is.True); + Assert.That(args.Command.CommandText.Contains($"[{Schema1}].[ConnectionOverrideTest.TestEntity]"), Is.True); } } @@ -85,7 +88,7 @@ public void OverwrittenConnectionTest() { var domainConfig = DomainConfigurationFactory.Create(); domainConfig.Types.Register(typeof(TestEntity)); - domainConfig.DefaultSchema = "dbo"; + domainConfig.DefaultSchema = dbo; domainConfig.UpgradeMode = DomainUpgradeMode.Recreate; var domainConnectionUrlString = domainConfig.ConnectionInfo.ConnectionUrl.ToString(); @@ -94,16 +97,16 @@ public void OverwrittenConnectionTest() var nodeConfig = new NodeConfiguration("Additional"); nodeConfig.UpgradeMode = DomainUpgradeMode.Recreate; nodeConfig.ConnectionInfo = new ConnectionInfo(UrlInfo.Parse(domainConnectionUrlString.Substring(0, parametersPosition))); - nodeConfig.SchemaMapping.Add("dbo", "Model1"); + nodeConfig.SchemaMapping.Add(dbo, Schema1); void commandValidator(object sender, DbCommandEventArgs args) { var session = ((SessionEventAccessor) sender).Session; if (session.StorageNodeId == WellKnown.DefaultNodeId) { - Assert.That(args.Command.CommandText.Contains("[dbo].[ConnectionOverrideTest.TestEntity]"), Is.True); + Assert.That(args.Command.CommandText.Contains($"[{dbo}].[ConnectionOverrideTest.TestEntity]"), Is.True); } else { - Assert.That(args.Command.CommandText.Contains("[Model1].[ConnectionOverrideTest.TestEntity]"), Is.True); + Assert.That(args.Command.CommandText.Contains($"[{Schema1}].[ConnectionOverrideTest.TestEntity]"), Is.True); } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/InitializationSqlOverrideTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/InitializationSqlOverrideTest.cs index a3d00af98c..313cab6ffc 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/InitializationSqlOverrideTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/InitializationSqlOverrideTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2020 Xtensive LLC. +// Copyright (C) 2020-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -27,6 +27,12 @@ public TestEntity(Session session) } } + private const string DOTestsDb = WellKnownDatabases.MultiDatabase.MainDb; + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + private const string Schema1 = WellKnownSchemas.Schema1; + [OneTimeSetUp] public void OneTimeSetUp() => Require.ProviderIs(StorageProvider.SqlServer); @@ -35,14 +41,14 @@ public void NullNodeInitSql() { var domainConfig = DomainConfigurationFactory.Create(); domainConfig.Types.Register(typeof(TestEntity)); - domainConfig.DefaultSchema = "dbo"; - domainConfig.ConnectionInitializationSql = "USE [DO-Tests]"; + domainConfig.DefaultSchema = dbo; + domainConfig.ConnectionInitializationSql = $"USE [{DOTestsDb}]"; domainConfig.UpgradeMode = DomainUpgradeMode.Recreate; var nodeConfig = new NodeConfiguration("Additional"); nodeConfig.UpgradeMode = DomainUpgradeMode.Recreate; nodeConfig.ConnectionInitializationSql = null; - nodeConfig.SchemaMapping.Add("dbo", "Model1"); + nodeConfig.SchemaMapping.Add(dbo, Schema1); using (var domain = Domain.Build(domainConfig)) { using (var session = domain.OpenSession()) @@ -51,7 +57,7 @@ public void NullNodeInitSql() using (var command = service.CreateCommand()) { command.CommandText = "SELECT DB_NAME() AS [Current Database];"; var databaseName = command.ExecuteScalar(); - Assert.That(databaseName, Is.EqualTo("DO-Tests")); + Assert.That(databaseName, Is.EqualTo(DOTestsDb)); } } @@ -63,7 +69,7 @@ public void NullNodeInitSql() using (var command = service.CreateCommand()) { command.CommandText = "SELECT DB_NAME() AS [Current Database];"; var databaseName = command.ExecuteScalar(); - Assert.That(databaseName, Is.EqualTo("DO-Tests")); + Assert.That(databaseName, Is.EqualTo(DOTestsDb)); } } } @@ -74,14 +80,14 @@ public void EmptyStringIninSql() { var domainConfig = DomainConfigurationFactory.Create(); domainConfig.Types.Register(typeof(TestEntity)); - domainConfig.DefaultSchema = "dbo"; - domainConfig.ConnectionInitializationSql = "USE [DO-Tests]"; + domainConfig.DefaultSchema = dbo; + domainConfig.ConnectionInitializationSql = $"USE [{DOTestsDb}]"; domainConfig.UpgradeMode = DomainUpgradeMode.Recreate; var nodeConfig = new NodeConfiguration("Additional"); nodeConfig.UpgradeMode = DomainUpgradeMode.Recreate; nodeConfig.ConnectionInitializationSql = string.Empty; - nodeConfig.SchemaMapping.Add("dbo", "Model1"); + nodeConfig.SchemaMapping.Add(dbo, Schema1); using (var domain = Domain.Build(domainConfig)) { using (var session = domain.OpenSession()) @@ -93,7 +99,7 @@ public void EmptyStringIninSql() using (var command = service.CreateCommand()) { command.CommandText = "SELECT DB_NAME() AS [Current Database];"; var databaseName = command.ExecuteScalar(); - Assert.That(databaseName, Is.EqualTo("DO-Tests")); + Assert.That(databaseName, Is.EqualTo(DOTestsDb)); } } @@ -105,7 +111,7 @@ public void EmptyStringIninSql() using (var command = service.CreateCommand()) { command.CommandText = "SELECT DB_NAME() AS [Current Database];"; var databaseName = command.ExecuteScalar(); - Assert.That(databaseName, Is.EqualTo("DO-Tests")); + Assert.That(databaseName, Is.EqualTo(DOTestsDb)); } } } @@ -116,14 +122,14 @@ public void ValidInitSql() { var domainConfig = DomainConfigurationFactory.Create(); domainConfig.Types.Register(typeof(TestEntity)); - domainConfig.DefaultSchema = "dbo"; - domainConfig.ConnectionInitializationSql = "USE [DO-Tests]"; + domainConfig.DefaultSchema = dbo; + domainConfig.ConnectionInitializationSql = $"USE [{DOTestsDb}]"; domainConfig.UpgradeMode = DomainUpgradeMode.Recreate; var nodeConfig = new NodeConfiguration("Additional"); nodeConfig.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfig.ConnectionInitializationSql = "USE [DO-Tests-1]"; - nodeConfig.SchemaMapping.Add("dbo", "dbo"); + nodeConfig.ConnectionInitializationSql = $"USE [{DOTests1Db}]"; + nodeConfig.SchemaMapping.Add(dbo, dbo); using (var domain = Domain.Build(domainConfig)) { using (var session = domain.OpenSession()) @@ -135,7 +141,7 @@ public void ValidInitSql() using (var command = service.CreateCommand()) { command.CommandText = "SELECT DB_NAME() AS [Current Database];"; var databaseName = command.ExecuteScalar(); - Assert.That(databaseName, Is.EqualTo("DO-Tests")); + Assert.That(databaseName, Is.EqualTo(DOTestsDb)); } } @@ -147,7 +153,7 @@ public void ValidInitSql() using (var command = service.CreateCommand()) { command.CommandText = "SELECT DB_NAME() AS [Current Database];"; var databaseName = command.ExecuteScalar(); - Assert.That(databaseName, Is.EqualTo("DO-Tests-1")); + Assert.That(databaseName, Is.EqualTo(DOTests1Db)); } } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/ObsoleteSelectStorageNodeTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/ObsoleteSelectStorageNodeTest.cs index 9fc8f3adaf..eed29b8bc1 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/ObsoleteSelectStorageNodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/ObsoleteSelectStorageNodeTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2014-2020 Xtensive LLC. +// Copyright (C) 2014-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -36,6 +36,8 @@ public class ObsoleteSelectStorageNodeTest : AutoBuildTest private const string AdditionalNodeName = "Additional"; private const string DefaultNodeTag = ""; private const string AdditionalNodeTag = ""; + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + private const string Schema1 = WellKnownSchemas.Schema1; protected override void CheckRequirements() { @@ -47,7 +49,7 @@ protected override DomainConfiguration BuildConfiguration() var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(TestEntity)); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = dbo; return configuration; } @@ -55,7 +57,7 @@ protected override Domain BuildDomain(DomainConfiguration configuration) { var domain = base.BuildDomain(configuration); var nodeConfig = new NodeConfiguration(AdditionalNodeName) { UpgradeMode = DomainUpgradeMode.Recreate }; - nodeConfig.SchemaMapping.Add("dbo", "Model1"); + nodeConfig.SchemaMapping.Add(dbo, Schema1); _ = domain.StorageNodeManager.AddNode(nodeConfig); return domain; } diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs index edd83ea992..f2f01899b0 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2019-2020 Xtensive LLC. +// Copyright (C) 2019-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -92,6 +92,10 @@ namespace Xtensive.Orm.Tests.Storage.Multinode { public sealed class QueryCachingTest : MultinodeTest { + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private readonly object SimpleQueryKey = new object(); private readonly object FilterByIdQueryKey = new object(); private readonly object FilterByManyIdsQueryKey = new object(); @@ -109,7 +113,7 @@ protected override DomainConfiguration BuildConfiguration() var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(BaseTestEntity).Assembly, typeof(BaseTestEntity).Namespace); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = dbo; return configuration; } @@ -117,13 +121,13 @@ protected override void PopulateNodes() { CustomUpgradeHandler.CurrentNodeId = TestNodeId2; var nodeConfiguration = new NodeConfiguration(TestNodeId2); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; _ = Domain.StorageNodeManager.AddNode(nodeConfiguration); CustomUpgradeHandler.CurrentNodeId = TestNodeId3; nodeConfiguration = new NodeConfiguration(TestNodeId3); - nodeConfiguration.SchemaMapping.Add("dbo", "Model2"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema2); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; _ = Domain.StorageNodeManager.AddNode(nodeConfiguration); } diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs index d9fc1d72d7..4537b8aa5e 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/SchemaMultinodeTest.cs @@ -13,9 +13,9 @@ namespace Xtensive.Orm.Tests.Storage.Multinode [TestFixture] public class SchemaMultinodeTest : StandardMultinodeTest { - private const string DefaultSchema = "Model1"; - private const string SecondSchema = "Model2"; - private const string ThirdSchema = "Model3"; + private const string DefaultSchema = WellKnownSchemas.Schema1; + private const string SecondSchema = WellKnownSchemas.Schema2; + private const string ThirdSchema = WellKnownSchemas.Schema3; protected override void CheckRequirements() { @@ -39,11 +39,11 @@ protected override void PopulateNodes() { var configuration = new NodeConfiguration(TestNodeId2) {UpgradeMode = DomainUpgradeMode.Recreate}; configuration.SchemaMapping.Add(DefaultSchema, SecondSchema); - Domain.StorageNodeManager.AddNode(configuration); + _ = Domain.StorageNodeManager.AddNode(configuration); configuration = new NodeConfiguration(TestNodeId3) {UpgradeMode = DomainUpgradeMode.Recreate}; configuration.SchemaMapping.Add(DefaultSchema, ThirdSchema); - Domain.StorageNodeManager.AddNode(configuration); + _ = Domain.StorageNodeManager.AddNode(configuration); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/StorageNodeManagerTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/StorageNodeManagerTest.cs index 2a97779306..1d9617ac4f 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/StorageNodeManagerTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/StorageNodeManagerTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2020 Xtensive LLC. +// Copyright (C) 2020-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -20,18 +20,21 @@ public class TestEntity : Entity public int Id { get; private set; } } + private const string DOTestsDb = WellKnownDatabases.MultiDatabase.MainDb; + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + private const string Schema1 = WellKnownSchemas.Schema1; + private readonly List NodesToClear = new List(); - protected override void CheckRequirements() - { - Require.ProviderIs(StorageProvider.SqlServer); - } + protected override void CheckRequirements() => Require.ProviderIs(StorageProvider.SqlServer); protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); config.Types.Register(typeof(TestEntity)); - config.DefaultSchema = "dbo"; + config.DefaultSchema = dbo; return config; } @@ -53,7 +56,7 @@ public void TearDown() public void AddUniqueNodeTest() { var nodeConfiguration = GetBaseNodeConfig(); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); var result = Domain.StorageNodeManager.AddNode(nodeConfiguration); Assert.That(result, Is.True); } @@ -62,7 +65,7 @@ public void AddUniqueNodeTest() public void AddAlreadyExistingTest() { var nodeConfiguration = GetBaseNodeConfig(); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); _ = Domain.StorageNodeManager.AddNode(nodeConfiguration); var sameConfig = (NodeConfiguration)nodeConfiguration.Clone(); @@ -74,7 +77,7 @@ public void AddAlreadyExistingTest() public void AddNodeWithNullNameTest() { var nodeConfiguration = new NodeConfiguration() { UpgradeMode = DomainUpgradeMode.Recreate }; - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); _ = Assert.Throws(() => Domain.StorageNodeManager.AddNode(nodeConfiguration)); } @@ -82,7 +85,7 @@ public void AddNodeWithNullNameTest() public void AddNodeWithEmptyNameTest() { var nodeConfiguration = new NodeConfiguration(string.Empty) { UpgradeMode = DomainUpgradeMode.Recreate }; - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); _ = Assert.Throws(() => Domain.StorageNodeManager.AddNode(nodeConfiguration)); } @@ -96,7 +99,7 @@ public void AddNodeWithNullConfigTest() public void AddNodeForMultidatabaseDomainTest() { var nodeConfiguration = new NodeConfiguration() { UpgradeMode = DomainUpgradeMode.Recreate }; - nodeConfiguration.DatabaseMapping.Add("DO-Tests", "DO-Tests-1"); + nodeConfiguration.DatabaseMapping.Add(DOTestsDb, DOTests1Db); _ = Assert.Throws(() => Domain.StorageNodeManager.AddNode(nodeConfiguration)); } @@ -110,7 +113,7 @@ public void GetNodeByNullStringTest() public void GetNodeByEmptyStringTest() { var nodeConfiguration = GetBaseNodeConfig(); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); var result = Domain.StorageNodeManager.AddNode(nodeConfiguration); Assert.That(result, Is.True); @@ -124,7 +127,7 @@ public void GetNodeByEmptyStringTest() public void GetNodeByExistingNodeNameTest() { var nodeConfiguration = GetBaseNodeConfig(); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); var result = Domain.StorageNodeManager.AddNode(nodeConfiguration); Assert.That(result, Is.True); @@ -138,7 +141,7 @@ public void GetNodeByExistingNodeNameTest() public void GetNodeWhichDoesntExistTest() { var nodeConfiguration = GetBaseNodeConfig(); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); var result = Domain.StorageNodeManager.AddNode(nodeConfiguration); Assert.That(result, Is.True); @@ -158,7 +161,7 @@ public void RemoveNodeWhichDoesntExistTest() public void RemoveExistingNode() { var nodeConfiguration = GetBaseNodeConfig(); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(dbo, Schema1); var result = Domain.StorageNodeManager.AddNode(nodeConfiguration); Assert.That(result, Is.True); diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/TypeIdAllocationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/TypeIdAllocationTest.cs index f0da469e62..865003b2a8 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/TypeIdAllocationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/TypeIdAllocationTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (C) 2015-2021 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 NUnit.Framework; @@ -13,8 +17,8 @@ namespace Xtensive.Orm.Tests.Storage.Multinode [TestFixture] public class TypeIdAllocationTest { - private const string FirstSchema = "Model1"; - private const string SecondSchema = "Model2"; + private const string FirstSchema = WellKnownSchemas.Schema1; + private const string SecondSchema = WellKnownSchemas.Schema2; [Test] public void RecreateTest() @@ -91,19 +95,31 @@ public void MainTest(Domain domain) var defaultNode = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var additionalNode = domain.StorageNodeManager.GetNode(FirstSchema) ?? domain.StorageNodeManager.GetNode(SecondSchema); var additionalNodeSchema = additionalNode.Id; - var defaultNodeSchema = additionalNode.Id==FirstSchema ? SecondSchema : FirstSchema; + var defaultNodeSchema = additionalNode.Id == FirstSchema ? SecondSchema : FirstSchema; if (!isRecreate) { - Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => e.TypeId==defaultNode.TypeIdRegistry[e]), Is.True); - Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => TypeIdentifierMapper.GetTypeId(e.UnderlyingType, defaultNodeSchema)==defaultNode.TypeIdRegistry[e])); - Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => e.TypeId!=additionalNode.TypeIdRegistry[e]), Is.True); - Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => TypeIdentifierMapper.GetTypeId(e.UnderlyingType, additionalNodeSchema)==additionalNode.TypeIdRegistry[e])); + Assert.That( + domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => e.TypeId == defaultNode.TypeIdRegistry[e]), + Is.True); + Assert.That( + domainModel.Types.Entities + .Where(e => !e.IsSystem) + .All(e => TypeIdentifierMapper.GetTypeId(e.UnderlyingType, defaultNodeSchema) == defaultNode.TypeIdRegistry[e]), + Is.True); + Assert.That( + domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => e.TypeId!=additionalNode.TypeIdRegistry[e]), + Is.True); + Assert.That( + domainModel.Types.Entities + .Where(e => !e.IsSystem) + .All(e => TypeIdentifierMapper.GetTypeId(e.UnderlyingType, additionalNodeSchema) == additionalNode.TypeIdRegistry[e]), + Is.True); } else { - Assert.That(domainModel.Types.Entities.All(e => e.TypeId==defaultNode.TypeIdRegistry[e]), Is.True); - Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => defaultNode.TypeIdRegistry[e] < 300)); - Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => e.TypeId==additionalNode.TypeIdRegistry[e]), Is.True); - Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => additionalNode.TypeIdRegistry[e]<300)); + Assert.That(domainModel.Types.Entities.All(e => e.TypeId == defaultNode.TypeIdRegistry[e]), Is.True); + Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => defaultNode.TypeIdRegistry[e] < 300), Is.True); + Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => e.TypeId == additionalNode.TypeIdRegistry[e]), Is.True); + Assert.That(domainModel.Types.Entities.Where(e => !e.IsSystem).All(e => additionalNode.TypeIdRegistry[e] < 300), Is.True); } } @@ -111,7 +127,7 @@ private Domain BuildMultinodeDomain(DomainUpgradeMode domainUpgradeMode, DomainU { var pair = BuildMultitnodeConfiguration(domainUpgradeMode, nodeUpgradeMode, masterSchema, slaveSchema); var domain = Domain.Build(pair.First); - domain.StorageNodeManager.AddNode(pair.Second); + _ = domain.StorageNodeManager.AddNode(pair.Second); return domain; } @@ -119,7 +135,9 @@ private void BuildInitialDomains() { foreach (var buildInitialConfiguration in BuildInitialConfigurations()) { using (var domain = Domain.Build(buildInitialConfiguration)) { - var verificationResult = domain.Model.Types.Entities.Where(e => !e.IsSystem).All(el => el.TypeId==TypeIdentifierMapper.GetTypeId(el.UnderlyingType, buildInitialConfiguration.DefaultSchema)); + var verificationResult = domain.Model.Types.Entities + .Where(e => !e.IsSystem) + .All(el => el.TypeId == TypeIdentifierMapper.GetTypeId(el.UnderlyingType, buildInitialConfiguration.DefaultSchema)); Assert.That(verificationResult, Is.True); } } @@ -136,26 +154,29 @@ private DomainConfiguration[] BuildInitialConfigurations() var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (Laptop).Assembly, typeof (Laptop).Namespace); + configuration.Types.Register(typeof(Laptop).Assembly, typeof(Laptop).Namespace); configuration.Name = "FirstSingleSchemaDomain"; - configuration.DefaultSchema = "Model1"; + configuration.DefaultSchema = FirstSchema; configurations[0] = configuration; configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (Laptop).Assembly, typeof (Laptop).Namespace); + configuration.Types.Register(typeof(Laptop).Assembly, typeof(Laptop).Namespace); configuration.Name = "SecondSingleSchemaDomain"; - configuration.DefaultSchema = "Model2"; + configuration.DefaultSchema = SecondSchema; configurations[1] = configuration; return configurations; } - private Pair BuildMultitnodeConfiguration(DomainUpgradeMode domainUpgradeMode, DomainUpgradeMode nodeUpgradeMode, string masterSchema, string slaveSchema) + private Pair BuildMultitnodeConfiguration( + DomainUpgradeMode domainUpgradeMode, + DomainUpgradeMode nodeUpgradeMode, + string masterSchema, string slaveSchema) { var configuration = DomainConfigurationFactory.Create(); configuration.DefaultSchema = masterSchema; - configuration.Types.Register(typeof (Laptop).Assembly, typeof (Laptop).Namespace); + configuration.Types.Register(typeof(Laptop).Assembly, typeof(Laptop).Namespace); configuration.UpgradeMode = domainUpgradeMode; configuration.Name = "MultiNodeDomain"; @@ -172,8 +193,8 @@ namespace Xtensive.Orm.Tests.Storage.Multinode.TypeIdExtractionTestModel { public class TypeIdentifierMapper { - private static Dictionary typeIdOffsetMap = new Dictionary(); - private static Dictionary typeIdOffsets = new Dictionary(); + private static readonly Dictionary typeIdOffsetMap = new Dictionary(); + private static readonly Dictionary typeIdOffsets = new Dictionary(); public static int GetTypeIdOffset(Type type) { @@ -183,10 +204,10 @@ public static int GetTypeIdOffset(Type type) public static int GetTypeId(Type type, string model) { var typeIdBase = typeIdOffsetMap[model]; - int typeIdOffset; - if (!typeIdOffsets.TryGetValue(type, out typeIdOffset)) - throw new InvalidOperationException(); - return typeIdBase + typeIdOffset; + if (typeIdOffsets.TryGetValue(type, out var typeIdOffset)) { + return typeIdBase + typeIdOffset; + } + throw new InvalidOperationException(); } private static void SetTypeOffsets(IDictionary typeMap) @@ -203,8 +224,8 @@ private static void SetTypeOffsets(IDictionary typeMap) private static void SetBaseTypeIds() { - typeIdOffsetMap["Model1"] = 300; - typeIdOffsetMap["Model2"] = 400; + typeIdOffsetMap[WellKnownSchemas.Schema1] = 300; + typeIdOffsetMap[WellKnownSchemas.Schema2] = 400; } static TypeIdentifierMapper() @@ -447,30 +468,27 @@ public enum StorageCapacityMeasure public class CustomUpgradeHandler : UpgradeHandler { - public override bool IsEnabled - { - get{ return UpgradeContext.Configuration.Name=="SecondSingleSchemaDomain" || UpgradeContext.Configuration.Name=="FirstSingleSchemaDomain";} - } - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool IsEnabled => + UpgradeContext.Configuration.Name == "SecondSingleSchemaDomain" + || UpgradeContext.Configuration.Name == "FirstSingleSchemaDomain"; + + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { - var isNodeBuilding = UpgradeContext.ParentDomain!=null; - var schemaName = (isNodeBuilding) + var isNodeBuilding = UpgradeContext.ParentDomain != null; + var schemaName = isNodeBuilding ? UpgradeContext.NodeConfiguration.SchemaMapping.Apply(UpgradeContext.Configuration.DefaultSchema) : UpgradeContext.Configuration.DefaultSchema; - UpgradeContext.UserDefinedTypeMap.Add(typeof (Laptop).FullName, TypeIdentifierMapper.GetTypeId(typeof (Laptop), schemaName)); - UpgradeContext.UserDefinedTypeMap.Add(typeof (Manufacturer).FullName, TypeIdentifierMapper.GetTypeId(typeof (Manufacturer), schemaName)); - UpgradeContext.UserDefinedTypeMap.Add(typeof (DisplayInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof (DisplayInfo), schemaName)); - UpgradeContext.UserDefinedTypeMap.Add(typeof (CPUInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof (CPUInfo), schemaName)); - UpgradeContext.UserDefinedTypeMap.Add(typeof (IOPortsInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof (IOPortsInfo), schemaName)); - UpgradeContext.UserDefinedTypeMap.Add(typeof (KeyboardInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof (KeyboardInfo), schemaName)); - UpgradeContext.UserDefinedTypeMap.Add(typeof (StorageInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof (StorageInfo), schemaName)); - UpgradeContext.UserDefinedTypeMap.Add(typeof (GraphicsCardInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof (GraphicsCardInfo), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(Laptop).FullName, TypeIdentifierMapper.GetTypeId(typeof(Laptop), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(Manufacturer).FullName, TypeIdentifierMapper.GetTypeId(typeof(Manufacturer), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(DisplayInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof(DisplayInfo), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(CPUInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof(CPUInfo), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(IOPortsInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof(IOPortsInfo), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(KeyboardInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof(KeyboardInfo), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(StorageInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof(StorageInfo), schemaName)); + UpgradeContext.UserDefinedTypeMap.Add(typeof(GraphicsCardInfo).FullName, TypeIdentifierMapper.GetTypeId(typeof(GraphicsCardInfo), schemaName)); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultidatabaseEntityManipulationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultidatabaseEntityManipulationTest.cs index ced8f8f632..21bf962276 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultidatabaseEntityManipulationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultidatabaseEntityManipulationTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017-2020 Xtensive LLC. +// Copyright (C) 2017-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -13,6 +13,16 @@ namespace Xtensive.Orm.Tests.Storage.SchemaSharing.EntityManipulation { public class MultidatabaseEntityManipulationTest : SimpleEntityManipulationTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override NodeConfigurationType NodeConfiguration => NodeConfigurationType.MultidatabaseNodes; protected override void CheckRequirements() => Require.AllFeaturesSupported(ProviderFeatures.Multidatabase); @@ -20,33 +30,33 @@ public class MultidatabaseEntityManipulationTest : SimpleEntityManipulationTest protected override void ApplyCustomSettingsToInitialConfiguration(DomainConfiguration configuration) { base.ApplyCustomSettingsToInitialConfiguration(configuration); - configuration.DefaultSchema = "Model1"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model3"); - configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model3"); + ApplyDomainCustomSettings(configuration); } protected override void ApplyCustomSettingsToTestConfiguration(DomainConfiguration configuration) { base.ApplyCustomSettingsToTestConfiguration(configuration); - configuration.DefaultSchema = "Model1"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model3"); - configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model3"); + ApplyDomainCustomSettings(configuration); + } + + private static void ApplyDomainCustomSettings(DomainConfiguration configuration) + { + configuration.DefaultSchema = Schema1; + configuration.DefaultDatabase = DOTests1Db; + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema3); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema3); } protected override IEnumerable GetNodes(DomainUpgradeMode upgradeMode) { var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; - additional.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-2"); - additional.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + additional.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + additional.DatabaseMapping.Add(DOTests1Db, DOTests4Db); + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new[] { @default, additional }; } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultischemaEntityManipulationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultischemaEntityManipulationTest.cs index d4c1a1bba6..d22d914b6e 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultischemaEntityManipulationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/MultischemaEntityManipulationTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017-2020 Xtensive LLC. +// Copyright (C) 2017-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -13,6 +13,11 @@ namespace Xtensive.Orm.Tests.Storage.SchemaSharing.EntityManipulation { public class MultischemaEntityManipulationTest : SimpleEntityManipulationTest { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override NodeConfigurationType NodeConfiguration => NodeConfigurationType.MultischemaNodes; protected override void CheckRequirements() => Require.AllFeaturesSupported(ProviderFeatures.Multischema); @@ -20,29 +25,29 @@ public class MultischemaEntityManipulationTest : SimpleEntityManipulationTest protected override void ApplyCustomSettingsToInitialConfiguration(DomainConfiguration configuration) { base.ApplyCustomSettingsToInitialConfiguration(configuration); - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema("Model3"); - configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema("Model3"); + configuration.DefaultSchema = Schema1; + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema(Schema3); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema(Schema3); } protected override void ApplyCustomSettingsToTestConfiguration(DomainConfiguration configuration) { base.ApplyCustomSettingsToTestConfiguration(configuration); - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema("Model3"); - configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema("Model3"); + configuration.DefaultSchema = Schema1; + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema(Schema3); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema(Schema3); } protected override IEnumerable GetNodes(DomainUpgradeMode upgradeMode) { var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new[] { @default, additional }; } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultidatabaseTest.cs index 8a04bab0c9..574a225259 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultidatabaseTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.06 @@ -14,6 +14,16 @@ namespace Xtensive.Orm.Tests.Storage.SchemaSharing.KeyGenerator { public class MultidatabaseTest : SimpleTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + private const string AdditionalNodeId = "Additional"; protected override void CheckRequirements() @@ -25,13 +35,13 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof (model.Part2.TestEntity3).Assembly, typeof (model.Part2.TestEntity3).Namespace).To("DO-Tests-1", "Model2"); - configuration.MappingRules.Map(typeof (model.Part3.TestEntity5).Assembly, typeof (model.Part3.TestEntity5).Namespace).To("DO-Tests-2", "Model1"); - configuration.MappingRules.Map(typeof (model.Part4.TestEntity7).Assembly, typeof (model.Part4.TestEntity7).Namespace).To("DO-Tests-2", "Model2"); + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity3).Assembly, typeof(model.Part2.TestEntity3).Namespace).To(DOTests1Db, Schema2); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity5).Assembly, typeof(model.Part3.TestEntity5).Namespace).To(DOTests2Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity7).Assembly, typeof(model.Part4.TestEntity7).Namespace).To(DOTests2Db, Schema2); - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.DefaultSchema = "Model1"; + configuration.DefaultDatabase = DOTests1Db; + configuration.DefaultSchema = Schema1; return configuration; } @@ -41,11 +51,11 @@ protected override Dictionary GetSkipParameters(DomainUp var additionalNode = new NodeConfiguration(AdditionalNodeId); additionalNode.UpgradeMode = upgradeMode; - additionalNode.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - additionalNode.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); + additionalNode.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + additionalNode.DatabaseMapping.Add(DOTests2Db, DOTests4Db); - additionalNode.SchemaMapping.Add("Model1", "Model3"); - additionalNode.SchemaMapping.Add("Model2", "Model4"); + additionalNode.SchemaMapping.Add(Schema1, Schema3); + additionalNode.SchemaMapping.Add(Schema2, Schema4); dictionary.Add(additionalNode, 7); return dictionary; diff --git a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultischemaTest.cs index 0b5772ec14..bb262c9543 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/KeyGenerator/MultischemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.06 @@ -15,6 +15,11 @@ namespace Xtensive.Orm.Tests.Storage.SchemaSharing.KeyGenerator { public class MultischemaTest : SimpleTest { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + private const string AdditionalNodeId = "Additional"; protected override void CheckRequirements() @@ -26,12 +31,12 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (model.Part2.TestEntity3).Assembly, typeof (model.Part2.TestEntity3).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (model.Part3.TestEntity5).Assembly, typeof (model.Part3.TestEntity5).Namespace).ToSchema("Model2"); - configuration.MappingRules.Map(typeof (model.Part4.TestEntity7).Assembly, typeof (model.Part4.TestEntity7).Namespace).ToSchema("Model2"); + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity3).Assembly, typeof(model.Part2.TestEntity3).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity5).Assembly, typeof(model.Part3.TestEntity5).Namespace).ToSchema(Schema2); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity7).Assembly, typeof(model.Part4.TestEntity7).Namespace).ToSchema(Schema2); - configuration.DefaultSchema = "Model1"; + configuration.DefaultSchema = Schema1; return configuration; } @@ -41,8 +46,8 @@ protected override Dictionary GetSkipParameters(DomainUp var additionalNode = new NodeConfiguration(AdditionalNodeId); additionalNode.UpgradeMode = upgradeMode; - additionalNode.SchemaMapping.Add("Model1", "Model3"); - additionalNode.SchemaMapping.Add("Model2", "Model4"); + additionalNode.SchemaMapping.Add(Schema1, Schema3); + additionalNode.SchemaMapping.Add(Schema2, Schema4); dictionary.Add(additionalNode, 7); return dictionary; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/BuildOnEmptySchemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/BuildOnEmptySchemaTest.cs index d22d64c0c8..509e3f5335 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/BuildOnEmptySchemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/BuildOnEmptySchemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.02.09 @@ -60,15 +60,12 @@ namespace CleanUpUpgrader { public class CleanupUpgradeHandler : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnComplete(Domain domain) { var cleanUpWorker = SqlWorker.Create(this.UpgradeContext.Services, SqlWorkerTask.DropSchema); - cleanUpWorker.Invoke(); + _ = cleanUpWorker.Invoke(); } } } @@ -121,7 +118,7 @@ protected Domain RebuildDomain(DomainConfiguration configuration) } catch (Exception e) { TestLog.Error(GetType().GetFullName()); - TestLog.Error(e); + _ = TestLog.Error(e); throw; } } @@ -130,8 +127,8 @@ protected Domain RebuildDomain(DomainConfiguration configuration) protected virtual void RegisterTypes(DomainConfiguration configuration) { - configuration.Types.Register(typeof (Symbol)); - configuration.Types.Register(typeof (Symbol2)); + configuration.Types.Register(typeof(Symbol)); + configuration.Types.Register(typeof(Symbol2)); } protected virtual void CheckRequirements(){} @@ -165,7 +162,7 @@ protected override void EnsureDomainWorksCorrectly(Domain domain) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { foreach (var intValue in Enumerable.Range(1000, 10)) { - Symbol.Intern(session, intValue.ToString()); + _ = Symbol.Intern(session, intValue.ToString()); } transaction.Complete(); } @@ -181,13 +178,16 @@ protected override void EnsureDomainWorksCorrectly(Domain domain) public sealed class MultischemaTest : BuildOnEmptySchemaBase { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + protected override void EnsureDomainWorksCorrectly(Domain domain) { using (domain) { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { foreach (var intValue in Enumerable.Range(1000, 10)) { - Symbol.Intern(session, intValue.ToString()); + _ = Symbol.Intern(session, intValue.ToString()); } transaction.Complete(); } @@ -208,18 +208,18 @@ protected override void CheckRequirements() protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof (Symbol).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (Symbol2).Namespace).ToSchema("Model2"); + configuration.DefaultSchema = Schema1; + configuration.MappingRules.Map(typeof(Symbol).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(Symbol2).Namespace).ToSchema(Schema2); return configuration; } protected override DomainConfiguration BuildInitialConfiguration() { var configuration = base.BuildInitialConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof (Symbol).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (Symbol2).Namespace).ToSchema("Model2"); + configuration.DefaultSchema = Schema1; + configuration.MappingRules.Map(typeof(Symbol).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(Symbol2).Namespace).ToSchema(Schema2); configuration.UpgradeMode = DomainUpgradeMode.Recreate; return configuration; } @@ -227,13 +227,18 @@ protected override DomainConfiguration BuildInitialConfiguration() public sealed class MultiDatabaseTest : BuildOnEmptySchemaBase { + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + + private const string DefauldSchema = WellKnownSchemas.Schema1; + protected override void EnsureDomainWorksCorrectly(Domain domain) { using (domain) { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { foreach (var intValue in Enumerable.Range(1000, 10)) { - Symbol.Intern(session, intValue.ToString()); + _ = Symbol.Intern(session, intValue.ToString()); } transaction.Complete(); } @@ -254,20 +259,20 @@ protected override void CheckRequirements() protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.DefaultDatabase = "DO-Tests"; - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof (Symbol).Namespace).ToDatabase("DO-Tests"); - configuration.MappingRules.Map(typeof (Symbol2).Namespace).ToDatabase("DO-Tests-1"); + configuration.DefaultDatabase = DOTests2Db; + configuration.DefaultSchema = DefauldSchema; + configuration.MappingRules.Map(typeof (Symbol).Namespace).ToDatabase(DOTests2Db); + configuration.MappingRules.Map(typeof (Symbol2).Namespace).ToDatabase(DOTests1Db); return configuration; } protected override DomainConfiguration BuildInitialConfiguration() { var configuration = base.BuildInitialConfiguration(); - configuration.DefaultDatabase = "DO-Tests"; - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof (Symbol).Namespace).ToDatabase("DO-Tests"); - configuration.MappingRules.Map(typeof (Symbol2).Namespace).ToDatabase("DO-Tests-1"); + configuration.DefaultDatabase = DOTests2Db; + configuration.DefaultSchema = DefauldSchema; + configuration.MappingRules.Map(typeof(Symbol).Namespace).ToDatabase(DOTests2Db); + configuration.MappingRules.Map(typeof(Symbol2).Namespace).ToDatabase(DOTests1Db); configuration.UpgradeMode = DomainUpgradeMode.Recreate; return configuration; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/CustomTypeIdMap/CustomTypeIdMap.cs b/Orm/Xtensive.Orm.Tests/Upgrade/CustomTypeIdMap/CustomTypeIdMap.cs index d979d72721..fd68d5d6da 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/CustomTypeIdMap/CustomTypeIdMap.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/CustomTypeIdMap/CustomTypeIdMap.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2014 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2014-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2014.07.18 @@ -98,20 +98,16 @@ namespace Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel2 { public class Upgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { base.OnPrepare(); - if (UpgradeContext.Configuration.UpgradeMode!=DomainUpgradeMode.Recreate) - { - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Author).FullName, 200); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Book).FullName, 201); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.BookInStore).FullName, 202); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Store).FullName, 203); + if (UpgradeContext.Configuration.UpgradeMode != DomainUpgradeMode.Recreate) { + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Author).FullName, 200); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Book).FullName, 201); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.BookInStore).FullName, 202); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Store).FullName, 203); UpgradeContext.UserDefinedTypeMap.Add("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book", 204); } } @@ -122,17 +118,14 @@ namespace Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel3 { public class OnlyCustomIdsUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Author).FullName, 200); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Book).FullName, 201); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.BookInStore).FullName, 202); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Store).FullName, 203); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Author).FullName, 200); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Book).FullName, 201); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.BookInStore).FullName, 202); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Store).FullName, 203); UpgradeContext.UserDefinedTypeMap.Add("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book", 204); } } @@ -142,15 +135,12 @@ namespace Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel4 { public class PartiallySequentialTypeIdsUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Author).FullName, 200); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Book).FullName, 201); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Author).FullName, 200); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Book).FullName, 201); } } } @@ -159,17 +149,14 @@ namespace Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel5 { public class PartiallyRandomTypeIdsUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Author).FullName, 150); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Book).FullName, 149); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Store).FullName, 250); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.BookInStore).FullName, 110); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Author).FullName, 150); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Book).FullName, 149); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Store).FullName, 250); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.BookInStore).FullName, 110); } } } @@ -178,15 +165,10 @@ namespace Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel6 { public class TypeIdForNotExistingTypeUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; - public override void OnPrepare() - { - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Author).FullName + "1", 100); - } + public override void OnPrepare() => + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Author).FullName + "1", 100); } } @@ -194,15 +176,12 @@ namespace Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel7 { public class TypeIdOutOfRangeUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.Author).FullName, 99); - UpgradeContext.UserDefinedTypeMap.Add(typeof (initialModel.BookInStore).FullName, 100); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.Author).FullName, 99); + UpgradeContext.UserDefinedTypeMap.Add(typeof(initialModel.BookInStore).FullName, 100); } } } @@ -240,15 +219,10 @@ public class Comment : Entity public class ConflictOfTypeIdUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; - public override void OnPrepare() - { - UpgradeContext.UserDefinedTypeMap.Add(typeof (Comment).FullName, 100); - } + public override void OnPrepare() => + UpgradeContext.UserDefinedTypeMap.Add(typeof(Comment).FullName, 100); } } @@ -302,15 +276,10 @@ public class User : Entity public class UpgradeWithNewTypeUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; - public override void OnPrepare() - { - UpgradeContext.UserDefinedTypeMap.Add(typeof (Comment).FullName, 110); - } + public override void OnPrepare() => + UpgradeContext.UserDefinedTypeMap.Add(typeof(Comment).FullName, 110); } } @@ -364,15 +333,12 @@ public class User : Entity public class UpgradeWithNewTypesUpgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { - UpgradeContext.UserDefinedTypeMap.Add(typeof (Comment).FullName, 110); - UpgradeContext.UserDefinedTypeMap.Add(typeof (User).FullName, 112); + UpgradeContext.UserDefinedTypeMap.Add(typeof(Comment).FullName, 110); + UpgradeContext.UserDefinedTypeMap.Add(typeof(User).FullName, 112); } } } @@ -404,16 +370,13 @@ public class Magazine : Entity public class Upgrader : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { - UpgradeContext.UserDefinedTypeMap.Add(typeof (Book).FullName, 100); - UpgradeContext.UserDefinedTypeMap.Add(typeof (Author).FullName, 101); - UpgradeContext.UserDefinedTypeMap.Add(typeof (Magazine).FullName, 102); + UpgradeContext.UserDefinedTypeMap.Add(typeof(Book).FullName, 100); + UpgradeContext.UserDefinedTypeMap.Add(typeof(Author).FullName, 101); + UpgradeContext.UserDefinedTypeMap.Add(typeof(Magazine).FullName, 102); if (UpgradeContext.Configuration.UpgradeMode.In(DomainUpgradeMode.LegacyValidate, DomainUpgradeMode.LegacySkip)) { UpgradeContext.UserDefinedTypeMap.Add("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel11.Database2.Parent", 200); UpgradeContext.UserDefinedTypeMap.Add("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel11.Database2.Child", 201); @@ -443,15 +406,9 @@ public class Child : Entity public class Upgrader : UpgradeHandler { - public override bool IsEnabled - { - get { return UpgradeContext.Configuration.UpgradeMode==DomainUpgradeMode.Recreate; } - } + public override bool IsEnabled => UpgradeContext.Configuration.UpgradeMode == DomainUpgradeMode.Recreate; - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { @@ -479,15 +436,9 @@ public class Engine : Entity public class Upgrader : UpgradeHandler { - public override bool IsEnabled - { - get { return UpgradeContext.Configuration.UpgradeMode==DomainUpgradeMode.Recreate; } - } + public override bool IsEnabled => UpgradeContext.Configuration.UpgradeMode == DomainUpgradeMode.Recreate; - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnPrepare() { @@ -504,187 +455,199 @@ namespace Xtensive.Orm.Tests.Upgrade [TestFixture] public class CustomTypeIdMap : AutoBuildTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + [Test] public void RecreateTest() { - var configuration = BuildConfiguration(typeof (initialModel.Author), typeof (onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.Recreate); + var configuration = BuildConfiguration(typeof(initialModel.Author), typeof(onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.Recreate); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 200); - Assert.AreEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + } + + Assert.AreEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (partialSequencialTypeIdModel.PartiallySequentialTypeIdsUpgrader), DomainUpgradeMode.Recreate); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(partialSequencialTypeIdModel.PartiallySequentialTypeIdsUpgrader), DomainUpgradeMode.Recreate); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 200); - Assert.AreEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); + } + + Assert.AreEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); } - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (partialRandomTypeIdModel.PartiallyRandomTypeIdsUpgrader), DomainUpgradeMode.Recreate); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(partialRandomTypeIdModel.PartiallyRandomTypeIdsUpgrader), DomainUpgradeMode.Recreate); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 110); - Assert.AreEqual(150, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(149, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreEqual(250, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreEqual(110, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + } + + Assert.AreEqual(150, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(149, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreEqual(250, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreEqual(110, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreEqual(251, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.Recreate); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.Recreate); + _ = Assert.Throws(() => BuildDomain(configuration)); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.Recreate); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.Recreate); + _ = Assert.Throws(() => BuildDomain(configuration)); } [Test] public void SkipTest() { BuildInitialDomain(); - var configuration = BuildConfiguration(typeof (initialModel.Author), DomainUpgradeMode.Skip); + var configuration = BuildConfiguration(typeof(initialModel.Author), DomainUpgradeMode.Skip); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.Skip); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.Skip); + _ = Assert.Throws(() => BuildDomain(configuration)); BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.Skip); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.Skip); + _ = Assert.Throws(() => BuildDomain(configuration)); } [Test] public void ValidateTest() { BuildInitialDomain(); - var configuration = BuildConfiguration(typeof (initialModel.Author), DomainUpgradeMode.Validate); + var configuration = BuildConfiguration(typeof(initialModel.Author), DomainUpgradeMode.Validate); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.Validate); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.Validate); + _ = Assert.Throws(() => BuildDomain(configuration)); BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.Validate); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.Validate); + _ = Assert.Throws(() => BuildDomain(configuration)); } [Test] public void PerformAndPerformSafelyTest() { BuildInitialDomain(); - var configuration = BuildConfiguration(typeof (initialModel.Author), DomainUpgradeMode.Perform); + var configuration = BuildConfiguration(typeof(initialModel.Author), DomainUpgradeMode.Perform); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), DomainUpgradeMode.PerformSafely); + configuration = BuildConfiguration(typeof(initialModel.Author), DomainUpgradeMode.PerformSafely); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.Perform); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.Perform); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.PerformSafely); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.PerformSafely); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (conflictModel.ConflictOfTypeIdUpgrader), DomainUpgradeMode.Perform); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(conflictModel.ConflictOfTypeIdUpgrader), DomainUpgradeMode.Perform); + _ = Assert.Throws(() => BuildDomain(configuration)); BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (conflictModel.ConflictOfTypeIdUpgrader), DomainUpgradeMode.PerformSafely); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(conflictModel.ConflictOfTypeIdUpgrader), DomainUpgradeMode.PerformSafely); + _ = Assert.Throws(() => BuildDomain(configuration)); BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (performWithNewType.UpgradeWithNewTypeUpgrader), DomainUpgradeMode.Perform); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(performWithNewType.UpgradeWithNewTypeUpgrader), DomainUpgradeMode.Perform); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); - Assert.AreEqual(110, domain.Model.Types[typeof (performWithNewType.Comment)].TypeId); - Assert.AreEqual(113, domain.Model.Types[typeof (performWithNewType.User)].TypeId); + Assert.AreEqual(110, domain.Model.Types[typeof(performWithNewType.Comment)].TypeId); + Assert.AreEqual(113, domain.Model.Types[typeof(performWithNewType.User)].TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (performWithNewType.UpgradeWithNewTypeUpgrader), DomainUpgradeMode.PerformSafely); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(performWithNewType.UpgradeWithNewTypeUpgrader), DomainUpgradeMode.PerformSafely); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); - Assert.AreEqual(110, domain.Model.Types[typeof (performWithNewType.Comment)].TypeId); - Assert.AreEqual(113, domain.Model.Types[typeof (performWithNewType.User)].TypeId); + Assert.AreEqual(110, domain.Model.Types[typeof(performWithNewType.Comment)].TypeId); + Assert.AreEqual(113, domain.Model.Types[typeof(performWithNewType.User)].TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (performWithNewTypes.UpgradeWithNewTypesUpgrader), DomainUpgradeMode.Perform); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(performWithNewTypes.UpgradeWithNewTypesUpgrader), DomainUpgradeMode.Perform); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); - Assert.AreEqual(110, domain.Model.Types[typeof (performWithNewTypes.Comment)].TypeId); - Assert.AreEqual(112, domain.Model.Types[typeof (performWithNewTypes.User)].TypeId); + Assert.AreEqual(110, domain.Model.Types[typeof(performWithNewTypes.Comment)].TypeId); + Assert.AreEqual(112, domain.Model.Types[typeof(performWithNewTypes.User)].TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (performWithNewTypes.UpgradeWithNewTypesUpgrader), DomainUpgradeMode.PerformSafely); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(performWithNewTypes.UpgradeWithNewTypesUpgrader), DomainUpgradeMode.PerformSafely); using (var domain = BuildDomain(configuration)) { - Assert.AreNotEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreNotEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreNotEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreNotEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + Assert.AreNotEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreNotEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreNotEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreNotEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreNotEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); - Assert.AreEqual(110, domain.Model.Types[typeof (performWithNewTypes.Comment)].TypeId); - Assert.AreEqual(112, domain.Model.Types[typeof (performWithNewTypes.User)].TypeId); + Assert.AreEqual(110, domain.Model.Types[typeof(performWithNewTypes.Comment)].TypeId); + Assert.AreEqual(112, domain.Model.Types[typeof(performWithNewTypes.User)].TypeId); } } @@ -692,90 +655,102 @@ public void PerformAndPerformSafelyTest() public void LegacySkipTest() { BuildInitialDomain(); - var configuration = BuildConfiguration(typeof (initialModel.Author), typeof (onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.LegacySkip); + var configuration = BuildConfiguration(typeof(initialModel.Author), typeof(onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.LegacySkip); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 200); - Assert.AreEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + } + + Assert.AreEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (partialSequencialTypeIdModel.PartiallySequentialTypeIdsUpgrader), DomainUpgradeMode.LegacySkip); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(partialSequencialTypeIdModel.PartiallySequentialTypeIdsUpgrader), DomainUpgradeMode.LegacySkip); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 200); - Assert.AreEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); + } + + Assert.AreEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (partialRandomTypeIdModel.PartiallyRandomTypeIdsUpgrader), DomainUpgradeMode.LegacySkip); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(partialRandomTypeIdModel.PartiallyRandomTypeIdsUpgrader), DomainUpgradeMode.LegacySkip); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 110); - Assert.AreEqual(150, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(149, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreEqual(250, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreEqual(110, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + } + + Assert.AreEqual(150, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(149, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreEqual(250, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreEqual(110, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreEqual(251, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.LegacySkip); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.LegacySkip); + _ = Assert.Throws(() => BuildDomain(configuration)); BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.LegacySkip); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.LegacySkip); + _ = Assert.Throws(() => BuildDomain(configuration)); } [Test] public void LegacyValidateTest() { BuildInitialDomain(); - var configuration = BuildConfiguration(typeof (initialModel.Author), typeof (onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.LegacyValidate); + var configuration = BuildConfiguration(typeof(initialModel.Author), typeof(onlyCustomsTypeIdsModel.OnlyCustomIdsUpgrader), DomainUpgradeMode.LegacyValidate); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 200); - Assert.AreEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreEqual(203, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreEqual(202, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + } + + Assert.AreEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreEqual(203, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreEqual(202, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreEqual(204, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (partialSequencialTypeIdModel.PartiallySequentialTypeIdsUpgrader), DomainUpgradeMode.LegacyValidate); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(partialSequencialTypeIdModel.PartiallySequentialTypeIdsUpgrader), DomainUpgradeMode.LegacyValidate); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 200); - Assert.AreEqual(200, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (initialModel.Book)].TypeId); + } + + Assert.AreEqual(200, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(initialModel.Book)].TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (partialRandomTypeIdModel.PartiallyRandomTypeIdsUpgrader), DomainUpgradeMode.LegacyValidate); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(partialRandomTypeIdModel.PartiallyRandomTypeIdsUpgrader), DomainUpgradeMode.LegacyValidate); using (var domain = BuildDomain(configuration)) { - foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) + foreach (var type in domain.Model.Types.Where(type => type.IsEntity && !type.IsSystem)) { Assert.GreaterOrEqual(type.TypeId, 110); - Assert.AreEqual(150, domain.Model.Types[typeof (initialModel.Author)].TypeId); - Assert.AreEqual(149, domain.Model.Types[typeof (initialModel.Book)].TypeId); - Assert.AreEqual(250, domain.Model.Types[typeof (initialModel.Store)].TypeId); - Assert.AreEqual(110, domain.Model.Types[typeof (initialModel.BookInStore)].TypeId); + } + + Assert.AreEqual(150, domain.Model.Types[typeof(initialModel.Author)].TypeId); + Assert.AreEqual(149, domain.Model.Types[typeof(initialModel.Book)].TypeId); + Assert.AreEqual(250, domain.Model.Types[typeof(initialModel.Store)].TypeId); + Assert.AreEqual(110, domain.Model.Types[typeof(initialModel.BookInStore)].TypeId); Assert.AreEqual(251, domain.Model.Types.Find("Xtensive.Orm.Tests.Upgrade.CustomTypeIdModel1.EntitySetItems.Author-Books-Book").TypeId); } BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.LegacyValidate); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeNotExistsModel.TypeIdForNotExistingTypeUpgrader), DomainUpgradeMode.LegacyValidate); + _ = Assert.Throws(() => BuildDomain(configuration)); BuildInitialDomain(); - configuration = BuildConfiguration(typeof (initialModel.Author), typeof (typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.LegacyValidate); - Assert.Throws(() => BuildDomain(configuration)); + configuration = BuildConfiguration(typeof(initialModel.Author), typeof(typeIdBeyongTheLimitsModel.TypeIdOutOfRangeUpgrader), DomainUpgradeMode.LegacyValidate); + _ = Assert.Throws(() => BuildDomain(configuration)); } [Test] @@ -785,39 +760,42 @@ public void LegacySkipMultiDatabaseTest() var expectedMap = new Dictionary(); BuildInitialDomains(); var firstConfiguration = DomainConfigurationFactory.Create(); - firstConfiguration.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); + firstConfiguration.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); firstConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - firstConfiguration.DefaultDatabase = "DO-Tests-2"; - firstConfiguration.DefaultSchema = "dbo"; - firstConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-2")); - using (var domain = BuildDomain(firstConfiguration)) + firstConfiguration.DefaultDatabase = DOTests2Db; + firstConfiguration.DefaultSchema = dbo; + firstConfiguration.Databases.Add(new DatabaseConfiguration(DOTests2Db)); + using (var domain = BuildDomain(firstConfiguration)) { expectedMap = domain.Model.Types.ToDictionary(key => key.UnderlyingType.FullName, value => value.TypeId); + } var secondConfiguration = DomainConfigurationFactory.Create(); - secondConfiguration.Types.Register(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace); - secondConfiguration.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); - secondConfiguration.Types.Register(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace); + secondConfiguration.Types.Register(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace); + secondConfiguration.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); + secondConfiguration.Types.Register(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace); secondConfiguration.UpgradeMode = DomainUpgradeMode.LegacySkip; - secondConfiguration.DefaultDatabase = "DO-Tests-2"; - secondConfiguration.DefaultSchema = "dbo"; - secondConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-1")); - secondConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-2")); - secondConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-3")); - secondConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace, "DO-Tests-1", "dbo")); - secondConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace, "DO-Tests-2", "dbo")); - secondConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace, "DO-Tests-3", "dbo")); + secondConfiguration.DefaultDatabase = DOTests2Db; + secondConfiguration.DefaultSchema = dbo; + secondConfiguration.Databases.Add(new DatabaseConfiguration(DOTests1Db)); + secondConfiguration.Databases.Add(new DatabaseConfiguration(DOTests2Db)); + secondConfiguration.Databases.Add(new DatabaseConfiguration(DOTests3Db)); + secondConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace, DOTests1Db, dbo)); + secondConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace, DOTests2Db, dbo)); + secondConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace, DOTests3Db, dbo)); using (var domain = BuildDomain(secondConfiguration)) { var currentMap = domain.Model.Types.ToDictionary(key => key.UnderlyingType.FullName, value => value.TypeId); - int typeId; foreach (var map in expectedMap) { - currentMap.TryGetValue(map.Key, out typeId); + _ = currentMap.TryGetValue(map.Key, out var typeId); Assert.AreEqual(map.Value, typeId); } - Assert.AreEqual(200, domain.Model.Types[typeof (multyDatabaseModel.Database2.Parent)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (multyDatabaseModel.Database2.Child)].TypeId); - Assert.AreEqual(300, domain.Model.Types[typeof (multyDatabaseModel.Database3.Car)].TypeId); - Assert.AreEqual(301, domain.Model.Types[typeof (multyDatabaseModel.Database3.Engine)].TypeId); + Assert.AreEqual(200, domain.Model.Types[typeof(multyDatabaseModel.Database2.Parent)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(multyDatabaseModel.Database2.Child)].TypeId); + Assert.AreEqual(300, domain.Model.Types[typeof(multyDatabaseModel.Database3.Car)].TypeId); + Assert.AreEqual(301, domain.Model.Types[typeof(multyDatabaseModel.Database3.Engine)].TypeId); } using (var domain = BuildDomain(firstConfiguration)) { @@ -828,28 +806,26 @@ public void LegacySkipMultiDatabaseTest() using (var domain = BuildDomain(secondConfiguration)) { var currentMap = domain.Model.Types.ToDictionary(key => key.UnderlyingType.FullName, value => value.TypeId); - int typeId; foreach (var map in expectedMap) { - currentMap.TryGetValue(map.Key, out typeId); + _ = currentMap.TryGetValue(map.Key, out var typeId); Assert.AreEqual(map.Value, typeId); } - Assert.AreEqual(200, domain.Model.Types[typeof (multyDatabaseModel.Database2.Parent)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (multyDatabaseModel.Database2.Child)].TypeId); - Assert.AreEqual(300, domain.Model.Types[typeof (multyDatabaseModel.Database3.Car)].TypeId); - Assert.AreEqual(301, domain.Model.Types[typeof (multyDatabaseModel.Database3.Engine)].TypeId); + Assert.AreEqual(200, domain.Model.Types[typeof(multyDatabaseModel.Database2.Parent)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(multyDatabaseModel.Database2.Child)].TypeId); + Assert.AreEqual(300, domain.Model.Types[typeof(multyDatabaseModel.Database3.Car)].TypeId); + Assert.AreEqual(301, domain.Model.Types[typeof(multyDatabaseModel.Database3.Engine)].TypeId); } using (var domain = BuildDomain(secondConfiguration)) { var currentMap = domain.Model.Types.ToDictionary(key => key.UnderlyingType.FullName, value => value.TypeId); foreach (var map in expectedMap) { - int typeId; - currentMap.TryGetValue(map.Key, out typeId); + _ = currentMap.TryGetValue(map.Key, out var typeId); Assert.AreEqual(map.Value, typeId); } - Assert.AreEqual(200, domain.Model.Types[typeof (multyDatabaseModel.Database2.Parent)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (multyDatabaseModel.Database2.Child)].TypeId); - Assert.AreEqual(300, domain.Model.Types[typeof (multyDatabaseModel.Database3.Car)].TypeId); - Assert.AreEqual(301, domain.Model.Types[typeof (multyDatabaseModel.Database3.Engine)].TypeId); + Assert.AreEqual(200, domain.Model.Types[typeof(multyDatabaseModel.Database2.Parent)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(multyDatabaseModel.Database2.Child)].TypeId); + Assert.AreEqual(300, domain.Model.Types[typeof(multyDatabaseModel.Database3.Car)].TypeId); + Assert.AreEqual(301, domain.Model.Types[typeof(multyDatabaseModel.Database3.Engine)].TypeId); } using (var domain = BuildDomain(firstConfiguration)) { @@ -858,18 +834,16 @@ public void LegacySkipMultiDatabaseTest() Assert.AreEqual(expectedMap, currentMap); } - using (var domain = BuildDomain(secondConfiguration)) - { + using (var domain = BuildDomain(secondConfiguration)) { var currentMap = domain.Model.Types.ToDictionary(key => key.UnderlyingType.FullName, value => value.TypeId); - int typeId; foreach (var map in expectedMap) { - currentMap.TryGetValue(map.Key, out typeId); + _ = currentMap.TryGetValue(map.Key, out var typeId); Assert.AreEqual(map.Value, typeId); } - Assert.AreEqual(200, domain.Model.Types[typeof (multyDatabaseModel.Database2.Parent)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (multyDatabaseModel.Database2.Child)].TypeId); - Assert.AreEqual(300, domain.Model.Types[typeof (multyDatabaseModel.Database3.Car)].TypeId); - Assert.AreEqual(301, domain.Model.Types[typeof (multyDatabaseModel.Database3.Engine)].TypeId); + Assert.AreEqual(200, domain.Model.Types[typeof(multyDatabaseModel.Database2.Parent)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(multyDatabaseModel.Database2.Child)].TypeId); + Assert.AreEqual(300, domain.Model.Types[typeof(multyDatabaseModel.Database3.Car)].TypeId); + Assert.AreEqual(301, domain.Model.Types[typeof(multyDatabaseModel.Database3.Engine)].TypeId); } } @@ -880,39 +854,42 @@ public void LegacyValidateMultiDatabaseTest() var expectedMap = new Dictionary(); BuildInitialDomains(); var firstConfiguration = DomainConfigurationFactory.Create(); - firstConfiguration.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); + firstConfiguration.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); firstConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - firstConfiguration.DefaultDatabase = "DO-Tests-2"; - firstConfiguration.DefaultSchema = "dbo"; - firstConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-2")); - using (var domain = BuildDomain(firstConfiguration)) + firstConfiguration.DefaultDatabase = DOTests2Db; + firstConfiguration.DefaultSchema = dbo; + firstConfiguration.Databases.Add(new DatabaseConfiguration(DOTests2Db)); + using (var domain = BuildDomain(firstConfiguration)) { expectedMap = domain.Model.Types.ToDictionary(key => key.UnderlyingType.FullName, value => value.TypeId); + } var secondConfiguration = DomainConfigurationFactory.Create(); - secondConfiguration.Types.Register(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace); - secondConfiguration.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); - secondConfiguration.Types.Register(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace); + secondConfiguration.Types.Register(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace); + secondConfiguration.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); + secondConfiguration.Types.Register(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace); secondConfiguration.UpgradeMode = DomainUpgradeMode.LegacyValidate; - secondConfiguration.DefaultDatabase = "DO-Tests-2"; - secondConfiguration.DefaultSchema = "dbo"; - secondConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-1")); - secondConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-2")); - secondConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-3")); - secondConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace, "DO-Tests-1", "dbo")); - secondConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace, "DO-Tests-2", "dbo")); - secondConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace, "DO-Tests-3", "dbo")); + secondConfiguration.DefaultDatabase = DOTests2Db; + secondConfiguration.DefaultSchema = dbo; + secondConfiguration.Databases.Add(new DatabaseConfiguration(DOTests1Db)); + secondConfiguration.Databases.Add(new DatabaseConfiguration(DOTests2Db)); + secondConfiguration.Databases.Add(new DatabaseConfiguration(DOTests3Db)); + secondConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace, DOTests1Db, dbo)); + secondConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace, DOTests2Db, dbo)); + secondConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace, DOTests3Db, dbo)); using (var domain = BuildDomain(secondConfiguration)) { var currentMap = domain.Model.Types.ToDictionary(key => key.UnderlyingType.FullName, value => value.TypeId); - int typeId; foreach (var map in expectedMap) { - currentMap.TryGetValue(map.Key, out typeId); + _ = currentMap.TryGetValue(map.Key, out var typeId); Assert.AreEqual(map.Value, typeId); } - Assert.AreEqual(200, domain.Model.Types[typeof (multyDatabaseModel.Database2.Parent)].TypeId); - Assert.AreEqual(201, domain.Model.Types[typeof (multyDatabaseModel.Database2.Child)].TypeId); - Assert.AreEqual(300, domain.Model.Types[typeof (multyDatabaseModel.Database3.Car)].TypeId); - Assert.AreEqual(301, domain.Model.Types[typeof (multyDatabaseModel.Database3.Engine)].TypeId); + Assert.AreEqual(200, domain.Model.Types[typeof(multyDatabaseModel.Database2.Parent)].TypeId); + Assert.AreEqual(201, domain.Model.Types[typeof(multyDatabaseModel.Database2.Child)].TypeId); + Assert.AreEqual(300, domain.Model.Types[typeof(multyDatabaseModel.Database3.Car)].TypeId); + Assert.AreEqual(301, domain.Model.Types[typeof(multyDatabaseModel.Database3.Engine)].TypeId); } } @@ -921,73 +898,84 @@ public void UserTypeIdLimits() { Require.AllFeaturesSupported(ProviderFeatures.Multidatabase | ProviderFeatures.Multischema); var rightConfiguration = DomainConfigurationFactory.Create(); - rightConfiguration.Types.Register(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace); - rightConfiguration.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); - rightConfiguration.Types.Register(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace); + rightConfiguration.Types.Register(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace); + rightConfiguration.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); + rightConfiguration.Types.Register(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace); rightConfiguration.UpgradeMode = DomainUpgradeMode.LegacyValidate; - rightConfiguration.DefaultDatabase = "DO-Tests-2"; - rightConfiguration.DefaultSchema = "dbo"; - rightConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-1") { MinTypeId = 200, MaxTypeId = 299 }); - rightConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-2") { MinTypeId = 100, MaxTypeId = 199 }); - rightConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-3") { MinTypeId = 300, MaxTypeId = 399 }); - rightConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace, "DO-Tests-1", "dbo")); - rightConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace, "DO-Tests-2", "dbo")); - rightConfiguration.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace, "DO-Tests-3", "dbo")); + rightConfiguration.DefaultDatabase = DOTests2Db; + rightConfiguration.DefaultSchema = dbo; + rightConfiguration.Databases.Add(new DatabaseConfiguration(DOTests1Db) { MinTypeId = 200, MaxTypeId = 299 }); + rightConfiguration.Databases.Add(new DatabaseConfiguration(DOTests2Db) { MinTypeId = 100, MaxTypeId = 199 }); + rightConfiguration.Databases.Add(new DatabaseConfiguration(DOTests3Db) { MinTypeId = 300, MaxTypeId = 399 }); + rightConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace, DOTests1Db, dbo)); + rightConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace, DOTests2Db, dbo)); + rightConfiguration.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace, DOTests3Db, dbo)); using (var domain = BuildDomain(rightConfiguration)) { } var wrongConfiguration1 = DomainConfigurationFactory.Create(); - wrongConfiguration1.Types.Register(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace); - wrongConfiguration1.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); - wrongConfiguration1.Types.Register(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace); + wrongConfiguration1.Types.Register(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace); + wrongConfiguration1.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); + wrongConfiguration1.Types.Register(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace); wrongConfiguration1.UpgradeMode = DomainUpgradeMode.LegacyValidate; - wrongConfiguration1.DefaultDatabase = "DO-Tests-2"; - wrongConfiguration1.DefaultSchema = "dbo"; - wrongConfiguration1.Databases.Add(new DatabaseConfiguration("DO-Tests-1") { MinTypeId = 500, MaxTypeId = 600 }); - wrongConfiguration1.Databases.Add(new DatabaseConfiguration("DO-Tests-2") { MinTypeId = 100, MaxTypeId = 199 }); - wrongConfiguration1.Databases.Add(new DatabaseConfiguration("DO-Tests-3") { MinTypeId = 300, MaxTypeId = 399 }); - wrongConfiguration1.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace, "DO-Tests-1", "dbo")); - wrongConfiguration1.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace, "DO-Tests-2", "dbo")); - wrongConfiguration1.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace, "DO-Tests-3", "dbo")); - Assert.Throws(() => BuildDomain(wrongConfiguration1)); + wrongConfiguration1.DefaultDatabase = DOTests2Db; + wrongConfiguration1.DefaultSchema = dbo; + wrongConfiguration1.Databases.Add(new DatabaseConfiguration(DOTests1Db) { MinTypeId = 500, MaxTypeId = 600 }); + wrongConfiguration1.Databases.Add(new DatabaseConfiguration(DOTests2Db) { MinTypeId = 100, MaxTypeId = 199 }); + wrongConfiguration1.Databases.Add(new DatabaseConfiguration(DOTests3Db) { MinTypeId = 300, MaxTypeId = 399 }); + wrongConfiguration1.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace, DOTests1Db, dbo)); + wrongConfiguration1.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace, DOTests2Db, dbo)); + wrongConfiguration1.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace, DOTests3Db, dbo)); + _ = Assert.Throws(() => BuildDomain(wrongConfiguration1)); var wrongConfiguration2 = DomainConfigurationFactory.Create(); - wrongConfiguration2.Types.Register(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace); - wrongConfiguration2.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); - wrongConfiguration2.Types.Register(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace); + wrongConfiguration2.Types.Register(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace); + wrongConfiguration2.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); + wrongConfiguration2.Types.Register(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace); wrongConfiguration2.UpgradeMode = DomainUpgradeMode.LegacyValidate; - wrongConfiguration2.DefaultDatabase = "DO-Tests-2"; - wrongConfiguration2.DefaultSchema = "dbo"; - wrongConfiguration2.Databases.Add(new DatabaseConfiguration("DO-Tests-1") { MinTypeId = 200, MaxTypeId = 299 }); - wrongConfiguration2.Databases.Add(new DatabaseConfiguration("DO-Tests-2") { MinTypeId = 500, MaxTypeId = 600 }); - wrongConfiguration2.Databases.Add(new DatabaseConfiguration("DO-Tests-3") { MinTypeId = 300, MaxTypeId = 399 }); - wrongConfiguration2.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace, "DO-Tests-1", "dbo")); - wrongConfiguration2.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace, "DO-Tests-2", "dbo")); - wrongConfiguration2.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace, "DO-Tests-3", "dbo")); - Assert.Throws(() => BuildDomain(wrongConfiguration2)); - + wrongConfiguration2.DefaultDatabase = DOTests2Db; + wrongConfiguration2.DefaultSchema = dbo; + wrongConfiguration2.Databases.Add(new DatabaseConfiguration(DOTests1Db) { MinTypeId = 200, MaxTypeId = 299 }); + wrongConfiguration2.Databases.Add(new DatabaseConfiguration(DOTests2Db) { MinTypeId = 500, MaxTypeId = 600 }); + wrongConfiguration2.Databases.Add(new DatabaseConfiguration(DOTests3Db) { MinTypeId = 300, MaxTypeId = 399 }); + wrongConfiguration2.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace, DOTests1Db, dbo)); + wrongConfiguration2.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace, DOTests2Db, dbo)); + wrongConfiguration2.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace, DOTests3Db, dbo)); + _ = Assert.Throws(() => BuildDomain(wrongConfiguration2)); var wrongConfiguration3 = DomainConfigurationFactory.Create(); - wrongConfiguration3.Types.Register(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace); - wrongConfiguration3.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); - wrongConfiguration3.Types.Register(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace); + wrongConfiguration3.Types.Register(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace); + wrongConfiguration3.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); + wrongConfiguration3.Types.Register(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace); wrongConfiguration3.UpgradeMode = DomainUpgradeMode.LegacyValidate; - wrongConfiguration3.DefaultDatabase = "DO-Tests-2"; - wrongConfiguration3.DefaultSchema = "dbo"; - wrongConfiguration3.Databases.Add(new DatabaseConfiguration("DO-Tests-1") { MinTypeId = 200, MaxTypeId = 299 }); - wrongConfiguration3.Databases.Add(new DatabaseConfiguration("DO-Tests-2") { MinTypeId = 100, MaxTypeId = 199 }); - wrongConfiguration3.Databases.Add(new DatabaseConfiguration("DO-Tests-3") { MinTypeId = 500, MaxTypeId = 600 }); - wrongConfiguration3.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace, "DO-Tests-1", "dbo")); - wrongConfiguration3.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace, "DO-Tests-2", "dbo")); - wrongConfiguration3.MappingRules.Add(new MappingRule(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace, "DO-Tests-3", "dbo")); - Assert.Throws(() => BuildDomain(wrongConfiguration3)); + wrongConfiguration3.DefaultDatabase = DOTests2Db; + wrongConfiguration3.DefaultSchema = dbo; + wrongConfiguration3.Databases.Add(new DatabaseConfiguration(DOTests1Db) { MinTypeId = 200, MaxTypeId = 299 }); + wrongConfiguration3.Databases.Add(new DatabaseConfiguration(DOTests2Db) { MinTypeId = 100, MaxTypeId = 199 }); + wrongConfiguration3.Databases.Add(new DatabaseConfiguration(DOTests3Db) { MinTypeId = 500, MaxTypeId = 600 }); + wrongConfiguration3.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace, DOTests1Db, dbo)); + wrongConfiguration3.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace, DOTests2Db, dbo)); + wrongConfiguration3.MappingRules.Add( + new MappingRule(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace, DOTests3Db, dbo)); + _ = Assert.Throws(() => BuildDomain(wrongConfiguration3)); } private void BuildInitialDomain() { var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (initialModel.Author).Assembly, typeof (initialModel.Author).Namespace); - configuration.Types.Register(typeof (initialModelUpgrader.Upgrader)); + configuration.Types.Register(typeof(initialModel.Author).Assembly, typeof(initialModel.Author).Namespace); + configuration.Types.Register(typeof(initialModelUpgrader.Upgrader)); configuration.UpgradeMode = DomainUpgradeMode.Recreate; using (var domain = BuildDomain(configuration)) { } } @@ -995,45 +983,44 @@ private void BuildInitialDomain() private void BuildInitialDomains() { var firstConfiguration = DomainConfigurationFactory.Create(); - firstConfiguration.Types.Register(typeof (multyDatabaseModel.Database1.Book).Assembly, typeof (multyDatabaseModel.Database1.Book).Namespace); + firstConfiguration.Types.Register(typeof(multyDatabaseModel.Database1.Book).Assembly, typeof(multyDatabaseModel.Database1.Book).Namespace); firstConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - firstConfiguration.DefaultDatabase = "DO-Tests-2"; - firstConfiguration.DefaultSchema = "dbo"; - firstConfiguration.Databases.Add(new DatabaseConfiguration("DO-Tests-2")); + firstConfiguration.DefaultDatabase = DOTests2Db; + firstConfiguration.DefaultSchema = dbo; + firstConfiguration.Databases.Add(new DatabaseConfiguration(DOTests2Db)); var domain1 = BuildDomain(firstConfiguration); domain1.Dispose(); var secondConfig = DomainConfigurationFactory.Create(); - secondConfig.Types.Register(typeof (multyDatabaseModel.Database2.Child).Assembly, typeof (multyDatabaseModel.Database2.Child).Namespace); + secondConfig.Types.Register(typeof(multyDatabaseModel.Database2.Child).Assembly, typeof(multyDatabaseModel.Database2.Child).Namespace); secondConfig.UpgradeMode = DomainUpgradeMode.Recreate; - secondConfig.DefaultDatabase = "DO-Tests-1"; - secondConfig.DefaultSchema = "dbo"; - secondConfig.Databases.Add(new DatabaseConfiguration("DO-Tests-1")); + secondConfig.DefaultDatabase = DOTests1Db; + secondConfig.DefaultSchema = dbo; + secondConfig.Databases.Add(new DatabaseConfiguration(DOTests1Db)); var domain2 = BuildDomain(secondConfig); domain2.Dispose(); var thirdConfig = DomainConfigurationFactory.Create(); - thirdConfig.Types.Register(typeof (multyDatabaseModel.Database3.Car).Assembly, typeof (multyDatabaseModel.Database3.Car).Namespace); + thirdConfig.Types.Register(typeof(multyDatabaseModel.Database3.Car).Assembly, typeof(multyDatabaseModel.Database3.Car).Namespace); thirdConfig.UpgradeMode = DomainUpgradeMode.Recreate; - thirdConfig.DefaultDatabase = "DO-Tests-3"; - thirdConfig.DefaultSchema = "dbo"; - thirdConfig.Databases.Add(new DatabaseConfiguration("DO-Tests-3")); + thirdConfig.DefaultDatabase = DOTests3Db; + thirdConfig.DefaultSchema = dbo; + thirdConfig.Databases.Add(new DatabaseConfiguration(DOTests3Db)); var domain3 = BuildDomain(thirdConfig); domain3.Dispose(); } - private DomainConfiguration BuildConfiguration(Type baseNamespaceType, DomainUpgradeMode mode) - { - return BuildConfiguration(baseNamespaceType, null, mode); - } + private DomainConfiguration BuildConfiguration(Type baseNamespaceType, DomainUpgradeMode mode) => + BuildConfiguration(baseNamespaceType, null, mode); private DomainConfiguration BuildConfiguration(Type baseNamespaceType, Type additionalNamespaceType, DomainUpgradeMode mode) { var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(baseNamespaceType.Assembly, baseNamespaceType.Namespace); - if (additionalNamespaceType!=null) + if (additionalNamespaceType != null) { configuration.Types.Register(additionalNamespaceType.Assembly, additionalNamespaceType.Namespace); + } configuration.UpgradeMode = mode; return configuration; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/FullText/DynamicFullTextCatalogTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/FullText/DynamicFullTextCatalogTest.cs index f8dbcdc1e0..23f087d4f7 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/FullText/DynamicFullTextCatalogTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/FullText/DynamicFullTextCatalogTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.07.12 @@ -151,6 +151,14 @@ namespace Xtensive.Orm.Tests.Upgrade [TestFixture] public class DynamicFullTextCatalogTest { + private const string DOTestsDb = WellKnownDatabases.MultiDatabase.MainDb; + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + [OneTimeSetUp] public void TestFixtureSetUp() { @@ -179,9 +187,9 @@ public void NoResolverTest() public void SingleSchemaTest() { var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (TestEntity)); - configuration.Types.Register(typeof (CustomUpgradeHandler)); - configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder)); + configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(CustomUpgradeHandler)); + configuration.Types.Register(typeof(CustomFullTextCatalogNameBuilder)); configuration.UpgradeMode = DomainUpgradeMode.Recreate; @@ -193,7 +201,7 @@ public void SingleSchemaTest() Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); var database = domain.StorageProviderInfo.DefaultDatabase; var schema = domain.StorageProviderInfo.DefaultSchema; - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_{1}", database, schema))); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{database}_{schema}")); } } @@ -202,10 +210,10 @@ public void SingleSchemaWithDatabaseSwitchTest() { Require.ProviderIs(StorageProvider.SqlServer); var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (TestEntity)); - configuration.Types.Register(typeof (CustomUpgradeHandler)); - configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder)); - configuration.ConnectionInitializationSql = "USE [DO-Tests-1]"; + configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(CustomUpgradeHandler)); + configuration.Types.Register(typeof(CustomFullTextCatalogNameBuilder)); + configuration.ConnectionInitializationSql = $"USE [{DOTests1Db}]"; configuration.UpgradeMode = DomainUpgradeMode.Recreate; using (var domain = Domain.Build(configuration)) { @@ -214,7 +222,7 @@ public void SingleSchemaWithDatabaseSwitchTest() var ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_dbo")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests1Db}_{dbo}")); } } @@ -223,22 +231,25 @@ public void MultischemaTest() { Require.AllFeaturesSupported(ProviderFeatures.Multischema); - var defaultSchemaType = typeof (Database1.Default.TestEntity1); - var model1Type = typeof (Database1.Model1.TestEntity2); - var model2Type = typeof (Database1.Model2.TestEntity3); + var defaultSchemaType = typeof(Database1.Default.TestEntity1); + var model1Type = typeof(Database1.Model1.TestEntity2); + var model2Type = typeof(Database1.Model2.TestEntity3); var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(defaultSchemaType); configuration.Types.Register(model1Type); configuration.Types.Register(model2Type); - configuration.Types.Register(typeof (CustomUpgradeHandler)); - configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder)); + configuration.Types.Register(typeof(CustomUpgradeHandler)); + configuration.Types.Register(typeof(CustomFullTextCatalogNameBuilder)); - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = dbo; - configuration.MappingRules.Map(defaultSchemaType.Assembly, defaultSchemaType.Namespace).ToSchema("dbo"); - configuration.MappingRules.Map(model1Type.Assembly, model1Type.Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(model2Type.Assembly, model2Type.Namespace).ToSchema("Model2"); + configuration.MappingRules.Map(defaultSchemaType.Assembly, defaultSchemaType.Namespace) + .ToSchema(dbo); + configuration.MappingRules.Map(model1Type.Assembly, model1Type.Namespace) + .ToSchema(WellKnownSchemas.Schema1); + configuration.MappingRules.Map(model2Type.Assembly, model2Type.Namespace) + .ToSchema(WellKnownSchemas.Schema2); configuration.UpgradeMode = DomainUpgradeMode.Recreate; @@ -246,23 +257,23 @@ public void MultischemaTest() var database = domain.StorageProviderInfo.DefaultDatabase; var targetModel = domain.Extensions.Get(); - var defaultSchemaTable = targetModel.Tables["dbo:TestEntity1"]; + var defaultSchemaTable = targetModel.Tables[$"{dbo}:TestEntity1"]; var ftIndex = defaultSchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_dbo", database))); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{database}_{dbo}")); - var model1SchemaTable = targetModel.Tables["Model1:TestEntity2"]; + var model1SchemaTable = targetModel.Tables[$"{Schema1}:TestEntity2"]; ftIndex = model1SchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_Model1", database))); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{database}_{Schema1}")); - var model2SchemaTable = targetModel.Tables["Model2:TestEntity3"]; + var model2SchemaTable = targetModel.Tables[$"{Schema2}:TestEntity3"]; ftIndex = model2SchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_Model2", database))); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{database}_{Schema2}")); } } @@ -270,13 +281,13 @@ public void MultischemaTest() public void MultidatabaseTest() { Require.AllFeaturesSupported(ProviderFeatures.Multidatabase); - var db1DefaultSchemaType = typeof (Database1.Default.TestEntity1); - var db1Model1SchemaType = typeof (Database1.Model1.TestEntity2); - var db1Model2SchemaType = typeof (Database1.Model2.TestEntity3); + var db1DefaultSchemaType = typeof(Database1.Default.TestEntity1); + var db1Model1SchemaType = typeof(Database1.Model1.TestEntity2); + var db1Model2SchemaType = typeof(Database1.Model2.TestEntity3); - var db2DefaultSchemaType = typeof (Database2.Default.TestEntity4); - var db2Model1SchemaType = typeof (Database2.Model1.TestEntity5); - var db2Model2SchemaType = typeof (Database2.Model2.TestEntity6); + var db2DefaultSchemaType = typeof(Database2.Default.TestEntity4); + var db2Model1SchemaType = typeof(Database2.Model1.TestEntity5); + var db2Model2SchemaType = typeof(Database2.Model2.TestEntity6); var configuragtion = DomainConfigurationFactory.Create(); configuragtion.Types.Register(db1DefaultSchemaType); @@ -287,61 +298,71 @@ public void MultidatabaseTest() configuragtion.Types.Register(db2Model1SchemaType); configuragtion.Types.Register(db2Model2SchemaType); - configuragtion.Types.Register(typeof (CustomUpgradeHandler)); - configuragtion.Types.Register(typeof (CustomFullTextCatalogNameBuilder)); + configuragtion.Types.Register(typeof(CustomUpgradeHandler)); + configuragtion.Types.Register(typeof(CustomFullTextCatalogNameBuilder)); - configuragtion.DefaultDatabase = "DO-Tests"; - configuragtion.DefaultSchema = "dbo"; + configuragtion.DefaultDatabase = DOTestsDb; + configuragtion.DefaultSchema = dbo; - configuragtion.MappingRules.Map(db1DefaultSchemaType.Assembly, db1DefaultSchemaType.Namespace).To("DO-Tests", "dbo"); - configuragtion.MappingRules.Map(db1Model1SchemaType.Assembly, db1Model1SchemaType.Namespace).To("DO-Tests", "Model1"); - configuragtion.MappingRules.Map(db1Model2SchemaType.Assembly, db1Model2SchemaType.Namespace).To("DO-Tests", "Model2"); + configuragtion.MappingRules.Map(db1DefaultSchemaType.Assembly, db1DefaultSchemaType.Namespace) + .To(DOTestsDb, dbo); + configuragtion.MappingRules.Map(db1Model1SchemaType.Assembly, db1Model1SchemaType.Namespace) + .To(DOTestsDb, WellKnownSchemas.Schema1); + configuragtion.MappingRules.Map(db1Model2SchemaType.Assembly, db1Model2SchemaType.Namespace) + .To(DOTestsDb, WellKnownSchemas.Schema2); - configuragtion.MappingRules.Map(db2DefaultSchemaType.Assembly, db2DefaultSchemaType.Namespace).To("DO-Tests-1", "dbo"); - configuragtion.MappingRules.Map(db2Model1SchemaType.Assembly, db2Model1SchemaType.Namespace).To("DO-Tests-1", "Model1"); - configuragtion.MappingRules.Map(db2Model2SchemaType.Assembly, db2Model2SchemaType.Namespace).To("DO-Tests-1", "Model2"); + configuragtion.MappingRules.Map(db2DefaultSchemaType.Assembly, db2DefaultSchemaType.Namespace) + .To(DOTests1Db, dbo); + configuragtion.MappingRules.Map(db2Model1SchemaType.Assembly, db2Model1SchemaType.Namespace) + .To(DOTests1Db, WellKnownSchemas.Schema1); + configuragtion.MappingRules.Map(db2Model2SchemaType.Assembly, db2Model2SchemaType.Namespace) + .To(DOTests1Db, WellKnownSchemas.Schema2); configuragtion.UpgradeMode = DomainUpgradeMode.Recreate; using (var domain = Domain.Build(configuragtion)) { var targetStorageModel = domain.Extensions.Get(); - var db1DefaultSchemaTable = targetStorageModel.Tables["DO-Tests:dbo:TestEntity1"]; + var db1DefaultSchemaTable = targetStorageModel + .Tables[$"{DOTestsDb}:{dbo}:TestEntity1"]; Assert.That(db1DefaultSchemaTable, Is.Not.Null); var ftIndex = db1DefaultSchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{dbo}")); - var db1Model1SchemaTable = targetStorageModel.Tables["DO-Tests:Model1:TestEntity2"]; + var db1Model1SchemaTable = targetStorageModel + .Tables[$"{DOTestsDb}:{Schema1}:TestEntity2"]; ftIndex = db1Model1SchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model1")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{Schema1}")); - var db1Model2SchemaTable = targetStorageModel.Tables["DO-Tests:Model2:TestEntity3"]; + var db1Model2SchemaTable = targetStorageModel + .Tables[$"{DOTestsDb}:{Schema2}:TestEntity3"]; ftIndex = db1Model2SchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model2")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{Schema2}")); - var db2DefaultSchemaTable = targetStorageModel.Tables["DO-Tests-1:dbo:TestEntity4"]; + var db2DefaultSchemaTable = targetStorageModel + .Tables[$"{DOTests1Db}:{dbo}:TestEntity4"]; ftIndex = db2DefaultSchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_dbo")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests1Db}_{dbo}")); - var db2Model1SchemaTable = targetStorageModel.Tables["DO-Tests-1:Model1:TestEntity5"]; + var db2Model1SchemaTable = targetStorageModel.Tables[$"{DOTests1Db}:{Schema1}:TestEntity5"]; ftIndex = db2Model1SchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model1")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests1Db}_{Schema1}")); - var db2Model2SchemaTable = targetStorageModel.Tables["DO-Tests-1:Model2:TestEntity6"]; + var db2Model2SchemaTable = targetStorageModel.Tables[$"{DOTests1Db}:{Schema2}:TestEntity6"]; ftIndex = db2Model2SchemaTable.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model2")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests1Db}_{Schema2}")); } } @@ -352,48 +373,48 @@ public void MultinodeTest1() var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (TestEntity)); - configuration.Types.Register(typeof (CustomUpgradeHandler)); - configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder)); + configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(CustomUpgradeHandler)); + configuration.Types.Register(typeof(CustomFullTextCatalogNameBuilder)); - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = dbo; var nodeConfiguration1 = new NodeConfiguration("AdditionalNode1"); nodeConfiguration1.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration1.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration1.SchemaMapping.Add(dbo, WellKnownSchemas.Schema1); var nodeConfiguration2 = new NodeConfiguration("AdditionalNode2"); nodeConfiguration2.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration2.SchemaMapping.Add("dbo", "Model2"); + nodeConfiguration2.SchemaMapping.Add(dbo, WellKnownSchemas.Schema2); using (var domain = Domain.Build(configuration)) { var domainStorageModel = domain.Extensions.Get(); - var table = domainStorageModel.Tables["dbo:TestEntity"]; + var table = domainStorageModel.Tables[$"{dbo}:TestEntity"]; Assert.That(table, Is.Not.Null); var ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{dbo}")); domain.Extensions.Clear(); - domain.StorageNodeManager.AddNode(nodeConfiguration1); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration1); var node1StorageModel = domain.Extensions.Get(); - table = node1StorageModel.Tables["Model1:TestEntity"]; + table = node1StorageModel.Tables[$"{Schema1}:TestEntity"]; Assert.That(table, Is.Not.Null); ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model1")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{Schema1}")); domain.Extensions.Clear(); - domain.StorageNodeManager.AddNode(nodeConfiguration2); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration2); var node2StorageModel = domain.Extensions.Get(); - table = node2StorageModel.Tables["Model2:TestEntity"]; + table = node2StorageModel.Tables[$"{Schema2}:TestEntity"]; Assert.That(table, Is.Not.Null); ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model2")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{Schema2}")); } } @@ -404,51 +425,51 @@ public void MultinodeTest2() var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (TestEntity)); - configuration.Types.Register(typeof (CustomUpgradeHandler)); - configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder)); + configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(CustomUpgradeHandler)); + configuration.Types.Register(typeof(CustomFullTextCatalogNameBuilder)); - configuration.DefaultSchema = "dbo"; - configuration.DefaultDatabase = "DO-Tests"; + configuration.DefaultSchema = dbo; + configuration.DefaultDatabase = DOTestsDb; var nodeConfiguration1 = new NodeConfiguration("AdditionalNode1"); nodeConfiguration1.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration1.SchemaMapping.Add("dbo", "Model1"); - nodeConfiguration1.DatabaseMapping.Add("DO-Tests", "DO-Tests-1"); + nodeConfiguration1.SchemaMapping.Add(dbo, WellKnownSchemas.Schema1); + nodeConfiguration1.DatabaseMapping.Add(DOTestsDb, DOTests1Db); var nodeConfiguration2 = new NodeConfiguration("AdditionalNode2"); nodeConfiguration2.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration2.SchemaMapping.Add("dbo", "Model2"); - nodeConfiguration2.DatabaseMapping.Add("DO-Tests", "DO-Tests-2"); + nodeConfiguration2.SchemaMapping.Add(dbo, WellKnownSchemas.Schema2); + nodeConfiguration2.DatabaseMapping.Add(DOTestsDb, DOTests2Db); using (var domain = Domain.Build(configuration)) { var domainStorageModel = domain.Extensions.Get(); - var table = domainStorageModel.Tables["DO-Tests:dbo:TestEntity"]; + var table = domainStorageModel.Tables[$"{DOTestsDb}:{dbo}:TestEntity"]; Assert.That(table, Is.Not.Null); var ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{dbo}")); domain.Extensions.Clear(); - domain.StorageNodeManager.AddNode(nodeConfiguration1); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration1); var node1StorageModel = domain.Extensions.Get(); - table = node1StorageModel.Tables["DO-Tests-1:Model1:TestEntity"]; + table = node1StorageModel.Tables[$"{DOTests1Db}:{Schema1}:TestEntity"]; Assert.That(table, Is.Not.Null); ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model1")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests1Db}_{Schema1}")); domain.Extensions.Clear(); - domain.StorageNodeManager.AddNode(nodeConfiguration2); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration2); var node2StorageModel = domain.Extensions.Get(); - table = node2StorageModel.Tables["DO-Tests-2:Model2:TestEntity"]; + table = node2StorageModel.Tables[$"{DOTests2Db}:{Schema2}:TestEntity"]; Assert.That(table, Is.Not.Null); ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-2_Model2")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests2Db}_{Schema2}")); } } @@ -459,50 +480,50 @@ public void MultinodeTest3() var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (TestEntity)); - configuration.Types.Register(typeof (CustomUpgradeHandler)); - configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder)); + configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(CustomUpgradeHandler)); + configuration.Types.Register(typeof(CustomFullTextCatalogNameBuilder)); - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = dbo; var nodeConfiguration1 = new NodeConfiguration("AdditionalNode1"); - nodeConfiguration1.ConnectionInitializationSql = "USE [DO-Tests-1]"; + nodeConfiguration1.ConnectionInitializationSql = $"USE [{DOTests1Db}]"; nodeConfiguration1.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration1.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration1.SchemaMapping.Add(dbo, WellKnownSchemas.Schema1); var nodeConfiguration2 = new NodeConfiguration("AdditionalNode2"); - nodeConfiguration2.ConnectionInitializationSql = "USE [DO-Tests-2]"; + nodeConfiguration2.ConnectionInitializationSql = $"USE [{DOTests2Db}]"; nodeConfiguration2.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration2.SchemaMapping.Add("dbo", "Model2"); + nodeConfiguration2.SchemaMapping.Add(dbo, WellKnownSchemas.Schema2); using (var domain = Domain.Build(configuration)) { var domainStorageModel = domain.Extensions.Get(); - var table = domainStorageModel.Tables["dbo:TestEntity"]; + var table = domainStorageModel.Tables[$"{dbo}:TestEntity"]; Assert.That(table, Is.Not.Null); var ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTestsDb}_{dbo}")); domain.Extensions.Clear(); - domain.StorageNodeManager.AddNode(nodeConfiguration1); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration1); var node1StorageModel = domain.Extensions.Get(); - table = node1StorageModel.Tables["Model1:TestEntity"]; + table = node1StorageModel.Tables[$"{Schema1}:TestEntity"]; Assert.That(table, Is.Not.Null); ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model1")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests1Db}_{Schema1}")); domain.Extensions.Clear(); - domain.StorageNodeManager.AddNode(nodeConfiguration2); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration2); var node2StorageModel = domain.Extensions.Get(); - table = node2StorageModel.Tables["Model2:TestEntity"]; + table = node2StorageModel.Tables[$"{Schema2}:TestEntity"]; Assert.That(table, Is.Not.Null); ftIndex = table.FullTextIndexes[0]; Assert.That(ftIndex, Is.Not.Null); Assert.That(ftIndex.FullTextCatalog, Is.Not.Null); - Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-2_Model2")); + Assert.That(ftIndex.FullTextCatalog, Is.EqualTo($"{DOTests2Db}_{Schema2}")); } } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultidatabaseTest.cs index a25e447a60..c19a6372b1 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultidatabaseTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2019-2020 Xtensive LLC. +// Copyright (C) 2019-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -20,14 +20,14 @@ namespace Xtensive.Orm.Tests.Upgrade.GeneratorUpgrade { public class MultidatabaseTest : SimpleSchemaTest { - private const string DefaultDatabase = "DO-Tests"; - private const string AlternativeDatabase = "DO-Tests-1"; + private const string DefaultDatabase = WellKnownDatabases.MultiDatabase.MainDb; + private const string AlternativeDatabase = WellKnownDatabases.MultiDatabase.AdditionalDb1; protected override void ApplyCustomConfigurationSettings(DomainConfiguration configuration) { base.ApplyCustomConfigurationSettings(configuration); configuration.DefaultDatabase = DefaultDatabase; - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; var namespaces = configuration.Types.GroupBy(t => t.Namespace).Select(g => g.Key).ToArray(); configuration.MappingRules.Map(namespaces[0]).ToDatabase(DefaultDatabase); configuration.MappingRules.Map(namespaces[0]).ToDatabase(AlternativeDatabase); diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultischemaTest.cs index 18f8e185b8..61b44ab7eb 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/MultischemaTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2019-2020 Xtensive LLC. +// Copyright (C) 2019-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -20,8 +20,8 @@ namespace Xtensive.Orm.Tests.Upgrade.GeneratorUpgrade { public class MultischemaTest : SimpleSchemaTest { - private const string DefaultSchema = "dbo"; - private const string AlternativeSchema = "Model1"; + private const string DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; + private const string AlternativeSchema = WellKnownSchemas.Schema1; protected override void ApplyCustomConfigurationSettings(DomainConfiguration configuration) { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/SimpleSchemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/SimpleSchemaTest.cs index f64691b53c..5ba0ec6c0b 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/SimpleSchemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/GeneratorUpgrade/SimpleSchemaTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2018-2020 Xtensive LLC. +// Copyright (C) 2018-2021 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 Kudelin @@ -37,7 +37,7 @@ protected virtual void ApplyCustomConfigurationSettings(DomainConfiguration conf { } - protected virtual string[] GetUsedCatalogs() => new[] { "DO-Tests" }; + protected virtual string[] GetUsedCatalogs() => new[] { WellKnownDatabases.MultiDatabase.MainDb }; [Test] public void NoChangesInGeneratorsTest1() diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/DatabasePerNodeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/DatabasePerNodeTest.cs index 4945fdde32..bf2bd2bed0 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/DatabasePerNodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/DatabasePerNodeTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -23,8 +23,8 @@ public sealed class DatabasePerNodeTest : HugeModelUpgradeTestBase protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.DefaultDatabase = "DO-Tests"; - configuration.DefaultSchema = "dbo"; + configuration.DefaultDatabase = WellKnownDatabases.MultiDatabase.MainDb; + configuration.DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; configuration.Types.Register(typeof(TestEntity0).Assembly, typeof(TestEntity0).Namespace); return configuration; } @@ -71,16 +71,21 @@ protected override void CheckIfQueriesWork(Domain domain) protected override IEnumerable GetAdditionalNodeConfigurations(DomainUpgradeMode upgradeMode) { var databases = new[] { - "DO-Tests-1", "DO-Tests-2", "DO-Tests-3", "DO-Tests-4", "DO-Tests-5", "DO-Tests-6", - "DO-Tests-7", "DO-Tests-8", "DO-Tests-9", "DO-Tests-10", "DO-Tests-11", "DO-Tests-12", + WellKnownDatabases.MultiDatabase.AdditionalDb1, WellKnownDatabases.MultiDatabase.AdditionalDb2, + WellKnownDatabases.MultiDatabase.AdditionalDb3, WellKnownDatabases.MultiDatabase.AdditionalDb4, + WellKnownDatabases.MultiDatabase.AdditionalDb5, WellKnownDatabases.MultiDatabase.AdditionalDb6, + WellKnownDatabases.MultiDatabase.AdditionalDb7, WellKnownDatabases.MultiDatabase.AdditionalDb8, + WellKnownDatabases.MultiDatabase.AdditionalDb9, WellKnownDatabases.MultiDatabase.AdditionalDb10, + WellKnownDatabases.MultiDatabase.AdditionalDb11, WellKnownDatabases.MultiDatabase.AdditionalDb12, }; var index = 0; foreach (var database in databases) { index++; - var node = new NodeConfiguration("Node" + index); - node.UpgradeMode = upgradeMode; - node.DatabaseMapping.Add("DO-Tests", database); + var node = new NodeConfiguration("Node" + index) { + UpgradeMode = upgradeMode + }; + node.DatabaseMapping.Add(WellKnownDatabases.MultiDatabase.MainDb, database); yield return node; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/MappedTypesNodesTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/MappedTypesNodesTest.cs index 4ebb4122b3..f6f5ae1a2a 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/MappedTypesNodesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/MappedTypesNodesTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -23,8 +23,8 @@ public sealed class MappedTypesNodesTest : HugeModelUpgradeTestBase protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.DefaultDatabase = "DO-Tests"; - configuration.DefaultSchema = "dbo"; + configuration.DefaultDatabase = WellKnownDatabases.MultiDatabase.MainDb; + configuration.DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; configuration.Types.Register(typeof(TestEntity0).Assembly, typeof(TestEntity0).Namespace); return configuration; } @@ -69,16 +69,21 @@ protected override void CheckIfQueriesWork(Domain domain) protected override IEnumerable GetAdditionalNodeConfigurations(DomainUpgradeMode upgradeMode) { var databases = new[] { - "DO-Tests-1", "DO-Tests-2", "DO-Tests-3", "DO-Tests-4", "DO-Tests-5", "DO-Tests-6", - "DO-Tests-7", "DO-Tests-8", "DO-Tests-9", "DO-Tests-10", "DO-Tests-11", "DO-Tests-12", + WellKnownDatabases.MultiDatabase.AdditionalDb1, WellKnownDatabases.MultiDatabase.AdditionalDb2, + WellKnownDatabases.MultiDatabase.AdditionalDb3, WellKnownDatabases.MultiDatabase.AdditionalDb4, + WellKnownDatabases.MultiDatabase.AdditionalDb5, WellKnownDatabases.MultiDatabase.AdditionalDb6, + WellKnownDatabases.MultiDatabase.AdditionalDb7, WellKnownDatabases.MultiDatabase.AdditionalDb8, + WellKnownDatabases.MultiDatabase.AdditionalDb9, WellKnownDatabases.MultiDatabase.AdditionalDb10, + WellKnownDatabases.MultiDatabase.AdditionalDb11, WellKnownDatabases.MultiDatabase.AdditionalDb12, }; var index = 0; foreach (var database in databases) { index++; - var node = new NodeConfiguration("Node" + index); - node.UpgradeMode = upgradeMode; - node.DatabaseMapping.Add("DO-Tests", database); + var node = new NodeConfiguration("Node" + index) { + UpgradeMode = upgradeMode + }; + node.DatabaseMapping.Add(WellKnownDatabases.MultiDatabase.MainDb, database); yield return node; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/SchemaPerNodeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/SchemaPerNodeTest.cs index 132af7be9a..59078ec59b 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/SchemaPerNodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/SchemaPerNodeTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -24,7 +24,7 @@ public sealed class SchemaPerNodeTest : HugeModelUpgradeTestBase protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; configuration.Types.Register(typeof(TestEntity0).Assembly, typeof(TestEntity0).Namespace); return configuration; } @@ -70,16 +70,19 @@ protected override void CheckIfQueriesWork(Domain domain) protected override IEnumerable GetAdditionalNodeConfigurations(DomainUpgradeMode upgradeMode) { var schemas = new[] { - "Model1", "Model2", "Model3", "Model4", "Model5", "Model6", - "Model7", "Model8", "Model9", "Model10", "Model11", "Model12", + WellKnownSchemas.Schema1, WellKnownSchemas.Schema2, WellKnownSchemas.Schema3, + WellKnownSchemas.Schema4, WellKnownSchemas.Schema5, WellKnownSchemas.Schema6, + WellKnownSchemas.Schema7, WellKnownSchemas.Schema8, WellKnownSchemas.Schema9, + WellKnownSchemas.Schema10, WellKnownSchemas.Schema11, WellKnownSchemas.Schema12, }; var index = 0; foreach (var schema in schemas) { index++; - var node = new NodeConfiguration("Node" + index); - node.UpgradeMode = upgradeMode; - node.SchemaMapping.Add("dbo", schema); + var node = new NodeConfiguration("Node" + index) { + UpgradeMode = upgradeMode + }; + node.SchemaMapping.Add(WellKnownSchemas.SqlServerDefaultSchema, schema); yield return node; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoDatabasesPerNodeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoDatabasesPerNodeTest.cs index de1b83d27b..7f7374dc70 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoDatabasesPerNodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoDatabasesPerNodeTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -23,8 +23,8 @@ public sealed class TwoDatabasesPerNodeTest : HugeModelUpgradeTestBase protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.DefaultDatabase = "DO-Tests"; - configuration.DefaultSchema = "dbo"; + configuration.DefaultDatabase = WellKnownDatabases.MultiDatabase.MainDb; + configuration.DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; var partOneType = typeof(TwoPartsModel.PartOne.TestEntityOne0); var partTwoType = typeof(TwoPartsModel.PartTwo.TestEntityTwo0); @@ -33,10 +33,10 @@ protected override DomainConfiguration BuildConfiguration() configuration.MappingRules .Map(partOneType.Assembly, partOneType.Namespace) - .ToDatabase("DO-Tests"); + .ToDatabase(WellKnownDatabases.MultiDatabase.MainDb); configuration.MappingRules .Map(partTwoType.Assembly, partTwoType.Namespace) - .ToDatabase("DO-Tests-1"); + .ToDatabase(WellKnownDatabases.MultiDatabase.AdditionalDb1); return configuration; } @@ -78,18 +78,19 @@ protected override void CheckIfQueriesWork(Domain domain) protected override IEnumerable GetAdditionalNodeConfigurations(DomainUpgradeMode upgradeMode) { var databases = new[] { - "DO-Tests-2", "DO-Tests-3", - "DO-Tests-4", "DO-Tests-5", - "DO-Tests-6", "DO-Tests-7", - "DO-Tests-8", "DO-Tests-9", - "DO-Tests-10", "DO-Tests-11", + WellKnownDatabases.MultiDatabase.AdditionalDb2, WellKnownDatabases.MultiDatabase.AdditionalDb3, + WellKnownDatabases.MultiDatabase.AdditionalDb4, WellKnownDatabases.MultiDatabase.AdditionalDb5, + WellKnownDatabases.MultiDatabase.AdditionalDb6, WellKnownDatabases.MultiDatabase.AdditionalDb7, + WellKnownDatabases.MultiDatabase.AdditionalDb8, WellKnownDatabases.MultiDatabase.AdditionalDb9, + WellKnownDatabases.MultiDatabase.AdditionalDb10, WellKnownDatabases.MultiDatabase.AdditionalDb11, }; for (int index = 0, nodeIndex=1 ; index < 10; index += 2, nodeIndex++) { - var node = new NodeConfiguration("Node" + nodeIndex); - node.UpgradeMode = upgradeMode; - node.DatabaseMapping.Add("DO-Tests", databases[index]); - node.DatabaseMapping.Add("DO-Tests-1", databases[index+1]); + var node = new NodeConfiguration("Node" + nodeIndex) { + UpgradeMode = upgradeMode + }; + node.DatabaseMapping.Add(WellKnownDatabases.MultiDatabase.MainDb, databases[index]); + node.DatabaseMapping.Add(WellKnownDatabases.MultiDatabase.AdditionalDb1, databases[index+1]); yield return node; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoSchemasPerNodeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoSchemasPerNodeTest.cs index d8d503144a..1ee0c02c72 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoSchemasPerNodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/HugeModelUpgrade/TwoSchemasPerNodeTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -27,7 +27,7 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; var partOneType = typeof(TwoPartsModel.PartOne.TestEntityOne0); var partTwoType = typeof(TwoPartsModel.PartTwo.TestEntityTwo0); @@ -36,10 +36,10 @@ protected override DomainConfiguration BuildConfiguration() configuration.MappingRules .Map(partOneType.Assembly, partOneType.Namespace) - .ToSchema("dbo"); + .ToSchema(WellKnownSchemas.SqlServerDefaultSchema); configuration.MappingRules .Map(partTwoType.Assembly, partTwoType.Namespace) - .ToSchema("Model1"); + .ToSchema(WellKnownSchemas.Schema1); return configuration; } @@ -81,18 +81,18 @@ protected override void CheckIfQueriesWork(Domain domain) protected override IEnumerable GetAdditionalNodeConfigurations(DomainUpgradeMode upgradeMode) { var schemas = new[] { - "Model2", "Model3", - "Model4", "Model5", - "Model6", "Model7", - "Model8", "Model9", - "Model10", "Model11", + WellKnownSchemas.Schema2, WellKnownSchemas.Schema3, + WellKnownSchemas.Schema4, WellKnownSchemas.Schema5, + WellKnownSchemas.Schema6, WellKnownSchemas.Schema7, + WellKnownSchemas.Schema8, WellKnownSchemas.Schema9, + WellKnownSchemas.Schema10, WellKnownSchemas.Schema11, }; for (int index = 0, nodeIndex = 1; index < 10; index += 2, nodeIndex++) { var node = new NodeConfiguration("Node" + nodeIndex); node.UpgradeMode = upgradeMode; - node.SchemaMapping.Add("dbo", schemas[index]); - node.SchemaMapping.Add("Model1", schemas[index + 1]); + node.SchemaMapping.Add(WellKnownSchemas.SqlServerDefaultSchema, schemas[index]); + node.SchemaMapping.Add(WellKnownSchemas.Schema1, schemas[index + 1]); yield return node; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultidatabaseDomainTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultidatabaseDomainTest.cs index 03a87cea66..555e65627a 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultidatabaseDomainTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultidatabaseDomainTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.02.24 @@ -21,6 +21,11 @@ namespace Xtensive.Orm.Tests.Upgrade.NewSkip /// public abstract class MultidatabaseDomainTest : SkipBuildingTestBase { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + + private const string DefaultSchema = WellKnownSchemas.Schema1; + private readonly string[] countries = new[] { "Russian Federation", "The United States of America", "Germany", "The United Kingdom" }; private readonly string[] positions = new[] { "Position1", "Position2", "Position3", "Position4" }; private readonly string[] emails = new[] { "aaaa@bbbb.ru", "bbbb@cccc.ru", "cccc@dddd.ru" }; @@ -56,40 +61,42 @@ protected override void PopulateData(Domain domain) protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (User).Assembly, typeof (User).Namespace); - configuration.Types.Register(typeof (Laptop).Assembly, typeof (Laptop).Namespace); - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.DefaultSchema = "Model1"; + configuration.Types.Register(typeof(User).Assembly, typeof(User).Namespace); + configuration.Types.Register(typeof(Laptop).Assembly, typeof(Laptop).Namespace); + configuration.DefaultDatabase = DOTests1Db; + configuration.DefaultSchema = DefaultSchema; configuration.ForeignKeyMode = GetForeignKeyMode(); - configuration.MappingRules.Map(typeof (User).Assembly, typeof (User).Namespace).ToDatabase("DO-Tests-1"); - configuration.MappingRules.Map(typeof (Laptop).Assembly, typeof (Laptop).Namespace).ToDatabase("DO-Tests-2"); + configuration.MappingRules.Map(typeof(User).Assembly, typeof(User).Namespace).ToDatabase(DOTests1Db); + configuration.MappingRules.Map(typeof(Laptop).Assembly, typeof(Laptop).Namespace).ToDatabase(DOTests2Db); return configuration; } private void PopulateDataForModel1() { - foreach (var position in positions) - new Position {Value = position}; + foreach (var position in positions) { + _ = new Position { Value = position }; + } - foreach (var country in countries) - new Country {Value = country}; + foreach (var country in countries) { + _ = new Country { Value = country }; + } - new SimpleFilterWithProperty {TestField = "hello world!"}; - new SimpleFilterWithProperty {TestField = "hello world!!"}; + _ = new SimpleFilterWithProperty { TestField = "hello world!" }; + _ = new SimpleFilterWithProperty { TestField = "hello world!!" }; var md5hash = new MD5Hash(); var buildInProvider = new BuildInProviderInfo(md5hash); - var googleProvider = new GoogleOAuthProvider(md5hash) {Url = "gooogle.com"}; - var aolProvider = new AolOpenIdProviderInfo(md5hash) {Url = "aol.com"}; - var providers = new ProviderInfo[] {buildInProvider, googleProvider, aolProvider}; + var googleProvider = new GoogleOAuthProvider(md5hash) { Url = "gooogle.com" }; + var aolProvider = new AolOpenIdProviderInfo(md5hash) { Url = "aol.com" }; + var providers = new ProviderInfo[] { buildInProvider, googleProvider, aolProvider }; for (var index = 0; index < names.Length; index++) { - var user = new User {Email = emails[index]}; - user.Person = new Person {FirstName = names[index].Split(' ')[0], LastName = names[index].Split(' ')[1]}; - user.AuthorizationInfos.Add(new AuthorizationInfo {Provider = providers[index]}); + var user = new User { Email = emails[index] }; + user.Person = new Person { FirstName = names[index].Split(' ')[0], LastName = names[index].Split(' ')[1] }; + _ = user.AuthorizationInfos.Add(new AuthorizationInfo { Provider = providers[index] }); } - new XType { + _ = new XType { FBool = true, FByte = 1, FSByte = 1, @@ -145,21 +152,21 @@ private void PopulateDataForModel1() private void PopulateDataForModel2() { - var amd = new Manufacturer {Name = "AMD"}; - var acer = new Manufacturer {Name = "Acer"}; - var intel = new Manufacturer {Name = "Intel"}; - var samsung = new Manufacturer {Name = "Samsung"}; - var seagate = new Manufacturer {Name = "Seagate"}; - var toshiba = new Manufacturer {Name = "Toshiba"}; - - var firstLaptop = new Laptop { + var amd = new Manufacturer { Name = "AMD" }; + var acer = new Manufacturer { Name = "Acer" }; + var intel = new Manufacturer { Name = "Intel" }; + var samsung = new Manufacturer { Name = "Samsung" }; + var seagate = new Manufacturer { Name = "Seagate" }; + var toshiba = new Manufacturer { Name = "Toshiba" }; + + _ = new Laptop { Manufacturer = samsung, SerialNumber = Guid.NewGuid().ToString(), DisplayInfo = new DisplayInfo { Dpi = 300, Format = Formats.Wide, - Manufacturer = new Manufacturer {Name = "FirstDisplayProducer"}, - Resolution = new Resolution {Wide = 1920, Hight = 1080}, + Manufacturer = new Manufacturer { Name = "FirstDisplayProducer" }, + Resolution = new Resolution { Wide = 1920, Hight = 1080 }, }, CpuInfo = new CPUInfo { ArchitectureName = "SuperDuperFastArchitecture", @@ -181,7 +188,7 @@ private void PopulateDataForModel2() GraphicsCardInfo = new GraphicsCardInfo { ChipProducer = ChipProducers.Amd, Name = "R9 370", - Vendor = new Manufacturer {Name = "Gigabyte"}, + Vendor = new Manufacturer { Name = "Gigabyte" }, }, IOPortsInfo = new IOPortsInfo { HasEthernetPort = true, @@ -198,14 +205,14 @@ private void PopulateDataForModel2() } }; - var secondLaptop = new Laptop { + _ = new Laptop { Manufacturer = acer, SerialNumber = Guid.NewGuid().ToString(), DisplayInfo = new DisplayInfo { Dpi = 300, Format = Formats.Wide, - Manufacturer = new Manufacturer {Name = "SecondDisplayProducer"}, - Resolution = new Resolution {Wide = 1920, Hight = 1080}, + Manufacturer = new Manufacturer { Name = "SecondDisplayProducer" }, + Resolution = new Resolution { Wide = 1920, Hight = 1080 }, }, CpuInfo = new CPUInfo { ArchitectureName = "BadassArchitecture", @@ -227,7 +234,7 @@ private void PopulateDataForModel2() GraphicsCardInfo = new GraphicsCardInfo { ChipProducer = ChipProducers.Amd, Name = "GTX 710", - Vendor = new Manufacturer {Name = "MSI"}, + Vendor = new Manufacturer { Name = "MSI" }, }, IOPortsInfo = new IOPortsInfo { HasEthernetPort = true, @@ -250,7 +257,7 @@ private void TestFirstModel(Session session) var countriesCount = session.Query.All().Count(); Assert.That(countriesCount, Is.EqualTo(countries.Length)); foreach (var country in countries) { - var c = session.Query.All().FirstOrDefault(el => el.Value==country); + var c = session.Query.All().FirstOrDefault(el => el.Value == country); Assert.That(c, Is.Not.Null); Assert.That(c.Value, Is.EqualTo(country)); } @@ -258,7 +265,7 @@ private void TestFirstModel(Session session) var positionsCount = session.Query.All().Count(); Assert.That(positionsCount, Is.EqualTo(positions.Length)); foreach (var position in positions) { - var p = session.Query.All().FirstOrDefault(el => el.Value==position); + var p = session.Query.All().FirstOrDefault(el => el.Value == position); Assert.That(p, Is.Not.Null); Assert.That(p.Value, Is.EqualTo(position)); } @@ -300,7 +307,7 @@ private void TestFirstModel(Session session) foreach (var name in names) { var firstName = name.Split(' ')[0]; var lastName = name.Split(' ')[1]; - var person = session.Query.All().FirstOrDefault(el => el.FirstName==firstName && el.LastName==lastName); + var person = session.Query.All().FirstOrDefault(el => el.FirstName == firstName && el.LastName == lastName); Assert.That(person, Is.Not.Null); Assert.That(person.User, Is.Not.Null); Assert.That(emails.Contains(person.User.Email), Is.True); @@ -362,23 +369,24 @@ private void TestFirstModel(Session session) Assert.That(x.FNEULong, Is.EqualTo(EULong.Min)); Assert.That(x.Ref, Is.Not.Null); - for (int i = 0; i < 200; i++) - new Country {Value = string.Format("Country{0}", i)}; + for (var i = 0; i < 200; i++) { + _ = new Country { Value = string.Format("Country{0}", i) }; + } } private void TestSecondModel(Session session) { var manufacturersCount = session.Query.All().Count(); Assert.That(manufacturersCount, Is.EqualTo(10)); - var amd = session.Query.All().First(el => el.Name=="AMD"); - var acer = session.Query.All().First(el => el.Name=="Acer"); - var intel = session.Query.All().First(el => el.Name=="Intel"); - var samsung = session.Query.All().First(el => el.Name=="Samsung"); - var seagate = session.Query.All().First(el => el.Name=="Seagate"); - var msi = session.Query.All().First(el => el.Name=="MSI"); - var gigabyte = session.Query.All().First(el => el.Name=="Gigabyte"); - var firstdisplayproducer = session.Query.All().First(el => el.Name=="FirstDisplayProducer"); - var seconddisplayproducer = session.Query.All().First(el => el.Name=="SecondDisplayProducer"); + var amd = session.Query.All().First(el => el.Name == "AMD"); + var acer = session.Query.All().First(el => el.Name == "Acer"); + var intel = session.Query.All().First(el => el.Name == "Intel"); + var samsung = session.Query.All().First(el => el.Name == "Samsung"); + var seagate = session.Query.All().First(el => el.Name == "Seagate"); + var msi = session.Query.All().First(el => el.Name == "MSI"); + var gigabyte = session.Query.All().First(el => el.Name == "Gigabyte"); + var firstdisplayproducer = session.Query.All().First(el => el.Name == "FirstDisplayProducer"); + var seconddisplayproducer = session.Query.All().First(el => el.Name == "SecondDisplayProducer"); var laptopCount = session.Query.All().Count(); Assert.That(laptopCount, Is.EqualTo(2)); @@ -400,8 +408,9 @@ private void TestSecondModel(Session session) var ioPostsInfosCount = session.Query.All().Count(); Assert.That(ioPostsInfosCount, Is.EqualTo(2)); - for (int i = 0; i < 200; i++) - new Manufacturer {Name = string.Format("Manufacturer{0}", i)}; + for (var i = 0; i < 200; i++) { + _ = new Manufacturer { Name = string.Format("Manufacturer{0}", i) }; + } } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultischemaDomainTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultischemaDomainTest.cs index 876aedca42..9864d2a375 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultischemaDomainTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/MultischemaDomainTest.cs @@ -1,3 +1,7 @@ +// Copyright (C) 2016-2021 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.Linq; using NUnit.Framework; @@ -15,6 +19,9 @@ namespace Xtensive.Orm.Tests.Upgrade.NewSkip /// public abstract class MultischemaDomainTest : SkipBuildingTestBase { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private readonly string[] countries = new[] { "Russian Federation", "The United States of America", "Germany", "The United Kingdom" }; private readonly string[] positions = new[] { "Position1", "Position2", "Position3", "Position4" }; private readonly string[] emails = new[] { "aaaa@bbbb.ru", "bbbb@cccc.ru", "cccc@dddd.ru" }; @@ -34,15 +41,11 @@ public void MainTest() [Test] public void CatalogComparisonTest() { - } protected abstract ForeignKeyMode GetForeignKeyMode(); - protected override void CheckRequirements() - { - Require.AllFeaturesSupported(ProviderFeatures.Multischema); - } + protected override void CheckRequirements() => Require.AllFeaturesSupported(ProviderFeatures.Multischema); protected override void PopulateData(Domain domain) { @@ -57,39 +60,41 @@ protected override void PopulateData(Domain domain) protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (User).Assembly, typeof (User).Namespace); - configuration.Types.Register(typeof (Laptop).Assembly, typeof (Laptop).Namespace); - configuration.DefaultSchema = "Model1"; + configuration.Types.Register(typeof(User).Assembly, typeof(User).Namespace); + configuration.Types.Register(typeof(Laptop).Assembly, typeof(Laptop).Namespace); + configuration.DefaultSchema = Schema1; configuration.ForeignKeyMode = GetForeignKeyMode(); - configuration.MappingRules.Map(typeof (User).Assembly, typeof (User).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (Laptop).Assembly, typeof (Laptop).Namespace).ToSchema("Model2"); + configuration.MappingRules.Map(typeof(User).Assembly, typeof(User).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(Laptop).Assembly, typeof(Laptop).Namespace).ToSchema(Schema2); return configuration; } private void PopulateDataForModel1() { - foreach (var position in positions) - new Position {Value = position}; + foreach (var position in positions) { + _ = new Position { Value = position }; + } - foreach (var country in countries) - new Country {Value = country}; + foreach (var country in countries) { + _ = new Country { Value = country }; + } - new SimpleFilterWithProperty {TestField = "hello world!"}; - new SimpleFilterWithProperty {TestField = "hello world!!"}; + _ = new SimpleFilterWithProperty { TestField = "hello world!" }; + _ = new SimpleFilterWithProperty { TestField = "hello world!!" }; var md5hash = new MD5Hash(); var buildInProvider = new BuildInProviderInfo(md5hash); - var googleProvider = new GoogleOAuthProvider(md5hash) {Url = "google.com"}; - var aolProvider = new AolOpenIdProviderInfo(md5hash) {Url = "aol.com"}; - var providers = new ProviderInfo[] {buildInProvider, googleProvider, aolProvider}; + var googleProvider = new GoogleOAuthProvider(md5hash) { Url = "google.com" }; + var aolProvider = new AolOpenIdProviderInfo(md5hash) { Url = "aol.com" }; + var providers = new ProviderInfo[] { buildInProvider, googleProvider, aolProvider }; for (var index = 0; index < names.Length; index++) { - var user = new User {Email = emails[index]}; - user.Person = new Person {FirstName = names[index].Split(' ')[0], LastName = names[index].Split(' ')[1]}; - user.AuthorizationInfos.Add(new AuthorizationInfo {Provider = providers[index]}); + var user = new User { Email = emails[index] }; + user.Person = new Person { FirstName = names[index].Split(' ')[0], LastName = names[index].Split(' ')[1] }; + _ = user.AuthorizationInfos.Add(new AuthorizationInfo { Provider = providers[index] }); } - new XType { + _ = new XType { FBool = true, FByte = 1, FSByte = 1, @@ -145,21 +150,21 @@ private void PopulateDataForModel1() private void PopulateDataForModel2() { - var amd = new Manufacturer {Name = "AMD"}; - var acer = new Manufacturer {Name = "Acer"}; - var intel = new Manufacturer {Name = "Intel"}; - var samsung = new Manufacturer {Name = "Samsung"}; - var seagate = new Manufacturer {Name = "Seagate"}; - var toshiba = new Manufacturer {Name = "Toshiba"}; - - var firstLaptop = new Laptop { + var amd = new Manufacturer { Name = "AMD" }; + var acer = new Manufacturer { Name = "Acer" }; + var intel = new Manufacturer { Name = "Intel" }; + var samsung = new Manufacturer { Name = "Samsung" }; + var seagate = new Manufacturer { Name = "Seagate" }; + var toshiba = new Manufacturer { Name = "Toshiba" }; + + _ = new Laptop { Manufacturer = samsung, SerialNumber = Guid.NewGuid().ToString(), DisplayInfo = new DisplayInfo { Dpi = 300, Format = Formats.Wide, - Manufacturer = new Manufacturer {Name = "FirstDisplayProducer"}, - Resolution = new Resolution {Wide = 1920, Hight = 1080}, + Manufacturer = new Manufacturer { Name = "FirstDisplayProducer" }, + Resolution = new Resolution { Wide = 1920, Hight = 1080 }, }, CpuInfo = new CPUInfo { ArchitectureName = "SuperDuperFastArchitecture", @@ -181,7 +186,7 @@ private void PopulateDataForModel2() GraphicsCardInfo = new GraphicsCardInfo { ChipProducer = ChipProducers.Amd, Name = "R9 370", - Vendor = new Manufacturer {Name = "Gigabyte"}, + Vendor = new Manufacturer { Name = "Gigabyte" }, }, IOPortsInfo = new IOPortsInfo { HasEthernetPort = true, @@ -198,14 +203,14 @@ private void PopulateDataForModel2() } }; - var secondLaptop = new Laptop { + _ = new Laptop { Manufacturer = acer, SerialNumber = Guid.NewGuid().ToString(), DisplayInfo = new DisplayInfo { Dpi = 300, Format = Formats.Wide, - Manufacturer = new Manufacturer {Name = "SecondDisplayProducer"}, - Resolution = new Resolution {Wide = 1920, Hight = 1080}, + Manufacturer = new Manufacturer { Name = "SecondDisplayProducer" }, + Resolution = new Resolution { Wide = 1920, Hight = 1080 }, }, CpuInfo = new CPUInfo { ArchitectureName = "BadassArchitecture", @@ -227,7 +232,7 @@ private void PopulateDataForModel2() GraphicsCardInfo = new GraphicsCardInfo { ChipProducer = ChipProducers.Amd, Name = "GTX 710", - Vendor = new Manufacturer {Name = "MSI"}, + Vendor = new Manufacturer { Name = "MSI" }, }, IOPortsInfo = new IOPortsInfo { HasEthernetPort = true, @@ -362,23 +367,24 @@ private void TestFirstModel(Session session) Assert.That(x.FNEULong, Is.EqualTo(EULong.Min)); Assert.That(x.Ref, Is.Not.Null); - for (int i = 0; i < 200; i++) - new Country {Value = string.Format("Country{0}", i)}; + for (var i = 0; i < 200; i++) { + _ = new Country {Value = string.Format("Country{0}", i)}; + } } private void TestSecondModel(Session session) { var manufacturersCount = session.Query.All().Count(); Assert.That(manufacturersCount, Is.EqualTo(10)); - var amd = session.Query.All().First(el => el.Name=="AMD"); - var acer = session.Query.All().First(el => el.Name=="Acer"); - var intel = session.Query.All().First(el => el.Name=="Intel"); - var samsung = session.Query.All().First(el => el.Name=="Samsung"); - var seagate = session.Query.All().First(el => el.Name=="Seagate"); - var msi = session.Query.All().First(el => el.Name=="MSI"); - var gigabyte = session.Query.All().First(el => el.Name=="Gigabyte"); - var firstdisplayproducer = session.Query.All().First(el => el.Name=="FirstDisplayProducer"); - var seconddisplayproducer = session.Query.All().First(el => el.Name=="SecondDisplayProducer"); + var amd = session.Query.All().First(el => el.Name == "AMD"); + var acer = session.Query.All().First(el => el.Name == "Acer"); + var intel = session.Query.All().First(el => el.Name == "Intel"); + var samsung = session.Query.All().First(el => el.Name == "Samsung"); + var seagate = session.Query.All().First(el => el.Name == "Seagate"); + var msi = session.Query.All().First(el => el.Name == "MSI"); + var gigabyte = session.Query.All().First(el => el.Name == "Gigabyte"); + var firstdisplayproducer = session.Query.All().First(el => el.Name == "FirstDisplayProducer"); + var seconddisplayproducer = session.Query.All().First(el => el.Name == "SecondDisplayProducer"); var laptopCount = session.Query.All().Count(); Assert.That(laptopCount, Is.EqualTo(2)); @@ -400,8 +406,9 @@ private void TestSecondModel(Session session) var ioPostsInfosCount = session.Query.All().Count(); Assert.That(ioPostsInfosCount, Is.EqualTo(2)); - for (int i = 0; i < 200; i++) - new Manufacturer {Name = string.Format("Manufacturer{0}", i)}; + for (var i = 0; i < 200; i++) { + _ = new Manufacturer { Name = string.Format("Manufacturer{0}", i) }; + } } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleDatabaseNodeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleDatabaseNodeTest.cs index e9157a9189..fb1b29c337 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleDatabaseNodeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleDatabaseNodeTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -18,9 +18,9 @@ namespace Xtensive.Orm.Tests.Upgrade.NewSkip { public abstract class SingleDatabaseNodeTest : SkipBuildingTestBase { - private const string DomainDatabase = "DO-Tests-1"; - private const string Node1Database = "DO-Tests-2"; - private const string Node2Database = "DO-Tests-3"; + private const string DomainDatabase = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string Node1Database = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string Node2Database = WellKnownDatabases.MultiDatabase.AdditionalDb3; private const string Node1Name = "Node1"; private const string Node2Name = "Node2"; @@ -69,7 +69,7 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(User).Assembly, typeof(User).Namespace); - configuration.DefaultDatabase = "DO-Tests-1"; + configuration.DefaultDatabase = DomainDatabase; configuration.ForeignKeyMode = GetForeignKeyMode(); return configuration; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleSchemaNodeBuildingTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleSchemaNodeBuildingTest.cs index 5397a6c277..72ee68630a 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleSchemaNodeBuildingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/SingleSchemaNodeBuildingTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2020 Xtensive LLC. +// Copyright (C) 2016-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -21,9 +21,9 @@ namespace Xtensive.Orm.Tests.Upgrade.NewSkip /// public abstract class SingleSchemaNodeTest : SkipBuildingTestBase { - private const string DomainSchema = "Model1"; - private const string Node1Schema = "Model2"; - private const string Node2Schema = "Model3"; + private const string DomainSchema = WellKnownSchemas.Schema1; + private const string Node1Schema = WellKnownSchemas.Schema2; + private const string Node2Schema = WellKnownSchemas.Schema3; private const string Node1Name = "Node1"; private const string Node2Name = "Node2"; @@ -72,7 +72,7 @@ protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(User).Assembly, typeof(User).Namespace); - configuration.DefaultSchema = "Model1"; + configuration.DefaultSchema = DomainSchema; configuration.ForeignKeyMode = GetForeignKeyMode(); return configuration; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/NodeBasedExtractedModelBuilderTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/NodeBasedExtractedModelBuilderTest.cs index b916f418ff..b4c5362cfd 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/NodeBasedExtractedModelBuilderTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/NodeBasedExtractedModelBuilderTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.12.13 @@ -44,86 +44,100 @@ namespace Xtensive.Orm.Tests.Upgrade { public class NodeBasedExtractedModelBuilderTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; + private const string Schema1 = WellKnownSchemas.Schema1; + [Test] public void MultischemaWithDatabaseSwitchingTest() { Require.ProviderIs(StorageProvider.SqlServer); var masterConnection = BuildConnectionToMaster(DomainConfigurationFactory.Create().ConnectionInfo); var configuration = new DomainConfiguration(masterConnection); - configuration.Types.Register(typeof (part1.TestEntity1)); + configuration.Types.Register(typeof(part1.TestEntity1)); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = "dbo"; - configuration.ConnectionInitializationSql = "USE [DO-Tests-1]"; + configuration.DefaultSchema = dbo; + configuration.ConnectionInitializationSql = $"USE [{DOTests1Db}]"; using (var domain = Domain.Build(configuration)) { - var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.ConnectionInfo = masterConnection; - domainCopyNode.ConnectionInitializationSql = "USE [DO-Tests-1]"; - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); - domainCopyNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(domainCopyNode); - - var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.ConnectionInfo = masterConnection; - anotherDatabaseNode.ConnectionInitializationSql = "USE [DO-Tests-2]"; - anotherDatabaseNode.SchemaMapping.Add("dbo", "dbo"); - anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); - - var thirdDatabaseNode = new NodeConfiguration("3"); - thirdDatabaseNode.ConnectionInfo = masterConnection; - thirdDatabaseNode.ConnectionInitializationSql = "USE [DO-Tests-3]"; - thirdDatabaseNode.SchemaMapping.Add("dbo", "Model1"); - thirdDatabaseNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(thirdDatabaseNode); + var domainCopyNode = new NodeConfiguration("1") { + ConnectionInfo = masterConnection, + ConnectionInitializationSql = $"USE [{DOTests1Db}]", + UpgradeMode = DomainUpgradeMode.Recreate + }; + domainCopyNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); + + var anotherDatabaseNode = new NodeConfiguration("2") { + ConnectionInfo = masterConnection, + ConnectionInitializationSql = $"USE [{DOTests2Db}]", + UpgradeMode = DomainUpgradeMode.Recreate + }; + anotherDatabaseNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); + + var thirdDatabaseNode = new NodeConfiguration("3") { + ConnectionInfo = masterConnection, + ConnectionInitializationSql = $"USE [{DOTests3Db}]", + UpgradeMode = DomainUpgradeMode.Recreate + }; + thirdDatabaseNode.SchemaMapping.Add(dbo, Schema1); + _ = domain.StorageNodeManager.AddNode(thirdDatabaseNode); } configuration = new DomainConfiguration(masterConnection); - configuration.Types.Register(typeof (part1.TestEntity1)); - configuration.DefaultSchema = "dbo"; + configuration.Types.Register(typeof(part1.TestEntity1)); + configuration.DefaultSchema = dbo; configuration.UpgradeMode = DomainUpgradeMode.Skip; - configuration.ConnectionInitializationSql = "USE [DO-Tests-1]"; + configuration.ConnectionInitializationSql = $"USE [{DOTests1Db}]"; using (var domain = Domain.Build(configuration)) { - var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.ConnectionInfo = masterConnection; - domainCopyNode.ConnectionInitializationSql = "USE [DO-Tests-1]"; - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); - domainCopyNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(domainCopyNode); - - var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.ConnectionInfo = masterConnection; - anotherDatabaseNode.ConnectionInitializationSql = "USE [DO-Tests-2]"; - anotherDatabaseNode.SchemaMapping.Add("dbo", "dbo"); - anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); - - var thirdDatabaseNode = new NodeConfiguration("3"); - thirdDatabaseNode.ConnectionInfo = masterConnection; - thirdDatabaseNode.ConnectionInitializationSql = "USE [DO-Tests-3]"; - thirdDatabaseNode.SchemaMapping.Add("dbo", "Model1"); - thirdDatabaseNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(thirdDatabaseNode); + var domainCopyNode = new NodeConfiguration("1") { + ConnectionInfo = masterConnection, + ConnectionInitializationSql = $"USE [{DOTests1Db}]", + UpgradeMode = DomainUpgradeMode.Skip + }; + domainCopyNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); + + var anotherDatabaseNode = new NodeConfiguration("2") { + ConnectionInfo = masterConnection, + ConnectionInitializationSql = $"USE [{DOTests2Db}]", + UpgradeMode = DomainUpgradeMode.Skip + }; + anotherDatabaseNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); + + var thirdDatabaseNode = new NodeConfiguration("3") { + ConnectionInfo = masterConnection, + ConnectionInitializationSql = $"USE [{DOTests3Db}]", + UpgradeMode = DomainUpgradeMode.Skip + }; + thirdDatabaseNode.SchemaMapping.Add(dbo, Schema1); + _ = domain.StorageNodeManager.AddNode(thirdDatabaseNode); var testEntity1Type = domain.Model.Types[typeof(part1.TestEntity1)]; var defaultNode = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var table = defaultNode.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); var node1 = domain.StorageNodeManager.GetNode("1"); table = node1.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); var node2 = domain.StorageNodeManager.GetNode("2"); table = node2.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node3 = domain.StorageNodeManager.GetNode("3"); table = node3.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("Model1")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-3")); + Assert.That(table.Schema.Name, Is.EqualTo(Schema1)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests3Db)); } } @@ -134,50 +148,48 @@ public void MultischemaWithoutDatabaseSwitchingTest() var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(typeof(part1.TestEntity1)); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = dbo; using (var domain = Domain.Build(configuration)) { var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); + domainCopyNode.SchemaMapping.Add(dbo, dbo); domainCopyNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(domainCopyNode); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.SchemaMapping.Add("dbo", "Model1"); + anotherDatabaseNode.SchemaMapping.Add(dbo, Schema1); anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); } configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(typeof(part1.TestEntity1)); - configuration.DefaultSchema = "dbo"; + configuration.DefaultSchema = dbo; configuration.UpgradeMode = DomainUpgradeMode.Skip; using (var domain = Domain.Build(configuration)) { - var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); - domainCopyNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(domainCopyNode); + var domainCopyNode = new NodeConfiguration("1") { UpgradeMode = DomainUpgradeMode.Skip }; + domainCopyNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); - var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.SchemaMapping.Add("dbo", "Model1"); - anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); + var anotherDatabaseNode = new NodeConfiguration("2") { UpgradeMode = DomainUpgradeMode.Skip }; + anotherDatabaseNode.SchemaMapping.Add(dbo, Schema1); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); - var testEntity1Type = domain.Model.Types[typeof (part1.TestEntity1)]; + var testEntity1Type = domain.Model.Types[typeof(part1.TestEntity1)]; var defaultNode = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var table = defaultNode.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(WellKnownDatabases.MultiDatabase.MainDb)); var node1 = domain.StorageNodeManager.GetNode("1"); table = node1.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(WellKnownDatabases.MultiDatabase.MainDb)); var node2 = domain.StorageNodeManager.GetNode("2"); table = node2.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("Model1")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests")); + Assert.That(table.Schema.Name, Is.EqualTo(Schema1)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(WellKnownDatabases.MultiDatabase.MainDb)); } } @@ -187,104 +199,110 @@ public void MultidatabaseNodesToOneDatabaseSetTest() Require.ProviderIs(StorageProvider.SqlServer); var masterConnectionInfo = BuildConnectionToMaster(DomainConfigurationFactory.Create().ConnectionInfo); - var configuration = new DomainConfiguration(masterConnectionInfo); - configuration.Types.Register(typeof (part1.TestEntity1)); - configuration.Types.Register(typeof (part2.TestEntity2)); - configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = "dbo"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof (part1.TestEntity1).Namespace).ToDatabase("DO-Tests-1"); - configuration.MappingRules.Map(typeof (part2.TestEntity2).Namespace).ToDatabase("DO-Tests-2"); + var configuration = new DomainConfiguration(masterConnectionInfo) { + UpgradeMode = DomainUpgradeMode.Recreate, + DefaultSchema = dbo, + DefaultDatabase = DOTests1Db + }; + configuration.Types.Register(typeof(part1.TestEntity1)); + configuration.Types.Register(typeof(part2.TestEntity2)); + configuration.MappingRules.Map(typeof(part1.TestEntity1).Namespace).ToDatabase(DOTests1Db); + configuration.MappingRules.Map(typeof(part2.TestEntity2).Namespace).ToDatabase(DOTests2Db); using (var domain = Domain.Build(configuration)) { - var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.ConnectionInfo = masterConnectionInfo; - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); - domainCopyNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(domainCopyNode); - - var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.ConnectionInfo = masterConnectionInfo; - anotherDatabaseNode.SchemaMapping.Add("dbo", "dbo"); - anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); + var domainCopyNode = new NodeConfiguration("1") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Recreate + }; + domainCopyNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); + + var anotherDatabaseNode = new NodeConfiguration("2") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Recreate + }; + anotherDatabaseNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); var testEntity1Type = domain.Model.Types[typeof(part1.TestEntity1)]; var testEntity2Type = domain.Model.Types[typeof(part2.TestEntity2)]; var defaultNode = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var table = defaultNode.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = defaultNode.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node1 = domain.StorageNodeManager.GetNode("1"); table = node1.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = node1.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node2 = domain.StorageNodeManager.GetNode("2"); table = node2.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = node2.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); } - configuration = new DomainConfiguration(masterConnectionInfo); + configuration = new DomainConfiguration(masterConnectionInfo) { + UpgradeMode = DomainUpgradeMode.Skip, + DefaultSchema = dbo, + DefaultDatabase = DOTests1Db + }; configuration.Types.Register(typeof(part1.TestEntity1)); configuration.Types.Register(typeof(part2.TestEntity2)); - configuration.UpgradeMode = DomainUpgradeMode.Skip; - configuration.DefaultSchema = "dbo"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof(part1.TestEntity1).Namespace).ToDatabase("DO-Tests-1"); - configuration.MappingRules.Map(typeof(part2.TestEntity2).Namespace).ToDatabase("DO-Tests-2"); + configuration.MappingRules.Map(typeof(part1.TestEntity1).Namespace).ToDatabase(DOTests1Db); + configuration.MappingRules.Map(typeof(part2.TestEntity2).Namespace).ToDatabase(DOTests2Db); using (var domain = Domain.Build(configuration)) { - var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.ConnectionInfo = masterConnectionInfo; - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); - domainCopyNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(domainCopyNode); - - var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.ConnectionInfo = masterConnectionInfo; - anotherDatabaseNode.SchemaMapping.Add("dbo", "dbo"); - anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); + var domainCopyNode = new NodeConfiguration("1") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Skip + }; + domainCopyNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); + + var anotherDatabaseNode = new NodeConfiguration("2") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Skip + }; + anotherDatabaseNode.SchemaMapping.Add(dbo, dbo); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); var testEntity1Type = domain.Model.Types[typeof(part1.TestEntity1)]; var testEntity2Type = domain.Model.Types[typeof(part2.TestEntity2)]; var defaultNode = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var table = defaultNode.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = defaultNode.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node1 = domain.StorageNodeManager.GetNode("1"); table = node1.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = node1.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node2 = domain.StorageNodeManager.GetNode("2"); table = node2.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = node2.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); } } @@ -294,112 +312,118 @@ public void MultidatabaseNodesToDifferentDatabaseSetTest() Require.ProviderIs(StorageProvider.SqlServer); var masterConnectionInfo = BuildConnectionToMaster(DomainConfigurationFactory.Create().ConnectionInfo); - var configuration = new DomainConfiguration(masterConnectionInfo); + var configuration = new DomainConfiguration(masterConnectionInfo) { + UpgradeMode = DomainUpgradeMode.Recreate, + DefaultSchema = dbo, + DefaultDatabase = DOTests1Db + }; configuration.Types.Register(typeof(part1.TestEntity1)); configuration.Types.Register(typeof(part2.TestEntity2)); - configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = "dbo"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof(part1.TestEntity1).Namespace).ToDatabase("DO-Tests-1"); - configuration.MappingRules.Map(typeof(part2.TestEntity2).Namespace).ToDatabase("DO-Tests-2"); + configuration.MappingRules.Map(typeof(part1.TestEntity1).Namespace).ToDatabase(DOTests1Db); + configuration.MappingRules.Map(typeof(part2.TestEntity2).Namespace).ToDatabase(DOTests2Db); using (var domain = Domain.Build(configuration)) { - var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.ConnectionInfo = masterConnectionInfo; - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); - domainCopyNode.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-1"); - domainCopyNode.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-2"); - domainCopyNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(domainCopyNode); - - var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.ConnectionInfo = masterConnectionInfo; - anotherDatabaseNode.SchemaMapping.Add("dbo", "dbo"); - anotherDatabaseNode.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - anotherDatabaseNode.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Recreate; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); + var domainCopyNode = new NodeConfiguration("1") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Recreate + }; + domainCopyNode.SchemaMapping.Add(dbo, dbo); + domainCopyNode.DatabaseMapping.Add(DOTests1Db, DOTests1Db); + domainCopyNode.DatabaseMapping.Add(DOTests2Db, DOTests2Db); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); + + var anotherDatabaseNode = new NodeConfiguration("2") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Recreate + }; + anotherDatabaseNode.SchemaMapping.Add(dbo, dbo); + anotherDatabaseNode.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + anotherDatabaseNode.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); var testEntity1Type = domain.Model.Types[typeof(part1.TestEntity1)]; var testEntity2Type = domain.Model.Types[typeof(part2.TestEntity2)]; var defaultNode = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var table = defaultNode.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = defaultNode.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node1 = domain.StorageNodeManager.GetNode("1"); table = node1.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = node1.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node2 = domain.StorageNodeManager.GetNode("2"); table = node2.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-3")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests3Db)); table = node2.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-4")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests4Db)); } - configuration = new DomainConfiguration(masterConnectionInfo); + configuration = new DomainConfiguration(masterConnectionInfo) { + UpgradeMode = DomainUpgradeMode.Skip, + DefaultSchema = dbo, + DefaultDatabase = DOTests1Db + }; configuration.Types.Register(typeof(part1.TestEntity1)); configuration.Types.Register(typeof(part2.TestEntity2)); - configuration.UpgradeMode = DomainUpgradeMode.Skip; - configuration.DefaultSchema = "dbo"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof(part1.TestEntity1).Namespace).ToDatabase("DO-Tests-1"); - configuration.MappingRules.Map(typeof(part2.TestEntity2).Namespace).ToDatabase("DO-Tests-2"); + configuration.MappingRules.Map(typeof(part1.TestEntity1).Namespace).ToDatabase(DOTests1Db); + configuration.MappingRules.Map(typeof(part2.TestEntity2).Namespace).ToDatabase(DOTests2Db); using (var domain = Domain.Build(configuration)) { - var domainCopyNode = new NodeConfiguration("1"); - domainCopyNode.ConnectionInfo = masterConnectionInfo; - domainCopyNode.SchemaMapping.Add("dbo", "dbo"); - domainCopyNode.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-1"); - domainCopyNode.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-2"); - domainCopyNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(domainCopyNode); - - var anotherDatabaseNode = new NodeConfiguration("2"); - anotherDatabaseNode.ConnectionInfo = masterConnectionInfo; - anotherDatabaseNode.SchemaMapping.Add("dbo", "dbo"); - anotherDatabaseNode.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - anotherDatabaseNode.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - anotherDatabaseNode.UpgradeMode = DomainUpgradeMode.Skip; - domain.StorageNodeManager.AddNode(anotherDatabaseNode); + var domainCopyNode = new NodeConfiguration("1") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Skip + }; + domainCopyNode.SchemaMapping.Add(dbo, dbo); + domainCopyNode.DatabaseMapping.Add(DOTests1Db, DOTests1Db); + domainCopyNode.DatabaseMapping.Add(DOTests2Db, DOTests2Db); + _ = domain.StorageNodeManager.AddNode(domainCopyNode); + + var anotherDatabaseNode = new NodeConfiguration("2") { + ConnectionInfo = masterConnectionInfo, + UpgradeMode = DomainUpgradeMode.Skip + }; + anotherDatabaseNode.SchemaMapping.Add(dbo, dbo); + anotherDatabaseNode.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + anotherDatabaseNode.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + _ = domain.StorageNodeManager.AddNode(anotherDatabaseNode); var testEntity1Type = domain.Model.Types[typeof(part1.TestEntity1)]; var testEntity2Type = domain.Model.Types[typeof(part2.TestEntity2)]; var defaultNode = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var table = defaultNode.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = defaultNode.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node1 = domain.StorageNodeManager.GetNode("1"); table = node1.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-1")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests1Db)); table = node1.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-2")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests2Db)); var node2 = domain.StorageNodeManager.GetNode("2"); table = node2.Mapping[testEntity1Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-3")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests3Db)); table = node2.Mapping[testEntity2Type]; - Assert.That(table.Schema.Name, Is.EqualTo("dbo")); - Assert.That(table.Schema.Catalog.Name, Is.EqualTo("DO-Tests-4")); + Assert.That(table.Schema.Name, Is.EqualTo(dbo)); + Assert.That(table.Schema.Catalog.Name, Is.EqualTo(DOTests4Db)); } } @@ -423,7 +447,7 @@ private ConnectionInfo BuildConnectionToMaster(ConnectionInfo connectionInfo) if (connectionInfo.ConnectionUrl.Params.Count > 0) { var stringBuilder = new StringBuilder("?"); foreach (var parameter in connectionInfo.ConnectionUrl.Params) { - stringBuilder.Append(string.Format(parameterTemplate, parameter.Key, parameter.Value)); + _ = stringBuilder.Append(string.Format(parameterTemplate, parameter.Key, parameter.Value)); } } return new ConnectionInfo(string.Format(connectionStringTemplate, protocol, loginInfo, server, database, parameters)); diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs index 48a94919c3..5807526541 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017-2020 Xtensive LLC. +// Copyright (C) 2017-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -19,6 +19,9 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing [TestFixture] public class IgnoreRulesTest : AutoBuildTest { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string MainNodeId = WellKnown.DefaultNodeId; private const string AdditionalNodeId = "Additional"; @@ -521,7 +524,7 @@ private SqlValueType GetTypeForString(int? length) => private Dictionary BuildNodeToSchemaMap() { return ProviderInfo.Supports(ProviderFeatures.Multischema) - ? new Dictionary {{MainNodeId, "Model1"}, {AdditionalNodeId, "Model2"}} + ? new Dictionary { { MainNodeId, Schema1 }, { AdditionalNodeId, Schema2 } } : new Dictionary(); } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MappingResolverTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MappingResolverTest.cs index e5898d80a7..c897c2b2dd 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MappingResolverTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MappingResolverTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.02 @@ -74,6 +74,16 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing [TestFixture] public class MappingResolverTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + private SqlDriver driver; [OneTimeSetUp] @@ -82,13 +92,12 @@ public void TestFixtureSetUp() driver = TestSqlDriver.Create(DomainConfigurationFactory.Create().ConnectionInfo); } - [Test] public void SimpleMappingResolverTest() { var domainConfiguration = DomainConfigurationFactory.Create(); domainConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - domainConfiguration.Types.Register(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace); + domainConfiguration.Types.Register(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace); using (var domain = Domain.Build(domainConfiguration)) { var node = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId); var nodeConfiguration = node.Configuration; @@ -120,7 +129,7 @@ public void SimpleMappingResolverTest() fullName = mappingResolver.GetNodeName(extractionResult.Catalogs.First().DefaultSchema.Tables["TestEntity1"]); Assert.That(fullName.ToLower(), Is.EqualTo("TestEntity1".ToLower())); - var typeInfo = domain.Model.Types[typeof (model.Part1.TestEntity1)]; + var typeInfo = domain.Model.Types[typeof(model.Part1.TestEntity1)]; fullName = mappingResolver.GetNodeName(typeInfo); Assert.That(fullName.ToLower(), Is.EqualTo("TestEntity1".ToLower())); @@ -149,25 +158,25 @@ public void MultischemaMappingResolverTest() var domainConfiguration = DomainConfigurationFactory.Create(); domainConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - domainConfiguration.Types.Register(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace); - domainConfiguration.Types.Register(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace); - domainConfiguration.Types.Register(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace); - domainConfiguration.Types.Register(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace); + domainConfiguration.Types.Register(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace); + domainConfiguration.Types.Register(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace); + domainConfiguration.Types.Register(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace); + domainConfiguration.Types.Register(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace); - domainConfiguration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).ToSchema("Model2"); - domainConfiguration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).ToSchema("Model2"); + domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema(Schema2); + domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema(Schema2); - domainConfiguration.DefaultSchema = "Model1"; + domainConfiguration.DefaultSchema = Schema1; var nodeConfiguration = new NodeConfiguration("Additional"); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration.SchemaMapping.Add("Model1", "Model3"); - nodeConfiguration.SchemaMapping.Add("Model2", "Model4"); + nodeConfiguration.SchemaMapping.Add(Schema1, Schema3); + nodeConfiguration.SchemaMapping.Add(Schema2, Schema4); using (var domain = Domain.Build(domainConfiguration)) { - domain.StorageNodeManager.AddNode(nodeConfiguration); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration); var defaultNodeConfig = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId).Configuration; var additionalNodeConfig = domain.StorageNodeManager.GetNode("Additional").Configuration; @@ -183,7 +192,10 @@ public void MultischemaMappingResolverTest() var additionalMappingResolver = MappingResolver.Create(domainConfiguration, additionalNodeConfig, defaultSchemaInfo); Assert.That(additionalMappingResolver, Is.InstanceOf()); - var resolverPerNodeMap = new Dictionary {{defaultNodeConfig, defaultMappingResolver}, {additionalNodeConfig, additionalMappingResolver}}; + var resolverPerNodeMap = new Dictionary { + { defaultNodeConfig, defaultMappingResolver }, + { additionalNodeConfig, additionalMappingResolver } + }; foreach (var pair in resolverPerNodeMap) { var nodeConfig = pair.Key; @@ -193,12 +205,12 @@ public void MultischemaMappingResolverTest() var metadataExtactionTasks = mappingResolver.GetMetadataTasks(); Assert.That(metadataExtactionTasks.Count(), Is.EqualTo(1)); Assert.That(metadataExtactionTasks.First().Catalog, Is.EqualTo(defaultSchemaInfo.Database)); - Assert.That(metadataExtactionTasks.First().Schema, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1"))); + Assert.That(metadataExtactionTasks.First().Schema, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1))); var schemaExtractionTasks = mappingResolver.GetSchemaTasks(); Assert.That(schemaExtractionTasks.Count(), Is.EqualTo(2)); - Assert.That(schemaExtractionTasks.Any(t => t.Catalog==defaultSchemaInfo.Database && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(schemaExtractionTasks.Any(t => t.Catalog==defaultSchemaInfo.Database && t.Schema==nodeConfig.SchemaMapping.Apply("Model2")), Is.True); + Assert.That(schemaExtractionTasks.Any(t => t.Catalog == defaultSchemaInfo.Database && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(schemaExtractionTasks.Any(t => t.Catalog == defaultSchemaInfo.Database && t.Schema == nodeConfig.SchemaMapping.Apply(Schema2)), Is.True); SchemaExtractionResult extractionResult; using (var connection = driver.CreateConnection()) { @@ -209,40 +221,40 @@ public void MultischemaMappingResolverTest() var fullName = mappingResolver.GetNodeName("dummy", "SchemaName", "Table1"); Assert.That(fullName, Is.EqualTo("SchemaName:Table1")); - fullName = mappingResolver.GetNodeName("dummy", "Model1", "Table1"); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1") + ":" + "Table1")); + fullName = mappingResolver.GetNodeName("dummy", Schema1, "Table1"); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1) + ":Table1")); - var productTable = extractionResult.Catalogs.First().Schemas[nodeConfig.SchemaMapping.Apply("Model1")].Tables["TestEntity1"]; + var productTable = extractionResult.Catalogs.First().Schemas[nodeConfig.SchemaMapping.Apply(Schema1)].Tables["TestEntity1"]; fullName = mappingResolver.GetNodeName(productTable); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1") + ":" + "TestEntity1")); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1) + ":TestEntity1")); - var currencyTable = extractionResult.Catalogs.First().Schemas[nodeConfig.SchemaMapping.Apply("Model2")].Tables["TestEntity4"]; + var currencyTable = extractionResult.Catalogs.First().Schemas[nodeConfig.SchemaMapping.Apply(Schema2)].Tables["TestEntity4"]; fullName = mappingResolver.GetNodeName(currencyTable); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model2") + ":" + "TestEntity4")); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema2) + ":TestEntity4")); var typeInfo = domain.Model.Types[typeof (model.Part1.TestEntity1)]; fullName = mappingResolver.GetNodeName(typeInfo); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1") + ":" + "TestEntity1")); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1) + ":TestEntity1")); var resolveResult = mappingResolver.Resolve(extractionResult, fullName); - Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1"))); + Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1))); var schema = mappingResolver.ResolveSchema(extractionResult, typeInfo.MappingDatabase, typeInfo.MappingSchema); - Assert.That(schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1"))); + Assert.That(schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1))); typeInfo = domain.Model.Types[typeof (model.Part4.TestEntity4)]; fullName = mappingResolver.GetNodeName(typeInfo); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model2") + ":" + "TestEntity4")); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema2) + ":TestEntity4")); resolveResult = mappingResolver.Resolve(extractionResult, fullName); - Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model2"))); + Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema2))); schema = mappingResolver.ResolveSchema(extractionResult, typeInfo.MappingDatabase, typeInfo.MappingSchema); - Assert.That(schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model2"))); + Assert.That(schema.GetNameInternal(), Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema2))); var sequence = typeInfo.Hierarchy.Key.Sequence; fullName = mappingResolver.GetNodeName(sequence); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1") + ":" + sequence.MappingName)); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1) + ":" + sequence.MappingName)); } } } @@ -255,22 +267,22 @@ public void MultischemaMappingResolverOnSharedSchemaTest() var domainConfiguration = DomainConfigurationFactory.Create(); domainConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - domainConfiguration.Types.Register(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace); - domainConfiguration.Types.Register(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace); - domainConfiguration.Types.Register(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace); - domainConfiguration.Types.Register(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace); + domainConfiguration.Types.Register(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace); + domainConfiguration.Types.Register(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace); + domainConfiguration.Types.Register(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace); + domainConfiguration.Types.Register(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace); - domainConfiguration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).ToSchema("Model2"); - domainConfiguration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).ToSchema("Model2"); + domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema(Schema2); + domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema(Schema2); - domainConfiguration.DefaultSchema = "Model1"; + domainConfiguration.DefaultSchema = Schema1; var nodeConfiguration = new NodeConfiguration("Additional"); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration.SchemaMapping.Add("Model1", "Model3"); - nodeConfiguration.SchemaMapping.Add("Model2", "Model4"); + nodeConfiguration.SchemaMapping.Add(Schema1, Schema3); + nodeConfiguration.SchemaMapping.Add(Schema2, Schema4); using (var domain = Domain.Build(domainConfiguration)) { domain.StorageNodeManager.AddNode(nodeConfiguration); @@ -294,9 +306,12 @@ public void MultischemaMappingResolverOnSharedSchemaTest() connection.Open(); extractionResult = new SchemaExtractionResult(driver.Extract(connection, defaultMappingResolver.GetSchemaTasks())); } - extractionResult.MakeShared(); + _ = extractionResult.MakeShared(); - var resolverPerNodeMap = new Dictionary {{defaultNodeConfig, defaultMappingResolver}, {additionalNodeConfig, additionalMappingResolver}}; + var resolverPerNodeMap = new Dictionary { + { defaultNodeConfig, defaultMappingResolver }, + { additionalNodeConfig, additionalMappingResolver } + }; foreach (var pair in resolverPerNodeMap) { var nodeConfig = pair.Key; @@ -306,53 +321,53 @@ public void MultischemaMappingResolverOnSharedSchemaTest() var metadataExtactionTasks = mappingResolver.GetMetadataTasks(); Assert.That(metadataExtactionTasks.Count(), Is.EqualTo(1)); Assert.That(metadataExtactionTasks.First().Catalog, Is.EqualTo(defaultSchemaInfo.Database)); - Assert.That(metadataExtactionTasks.First().Schema, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1"))); + Assert.That(metadataExtactionTasks.First().Schema, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1))); var schemaExtractionTasks = mappingResolver.GetSchemaTasks(); Assert.That(schemaExtractionTasks.Count(), Is.EqualTo(2)); - Assert.That(schemaExtractionTasks.Any(t => t.Catalog==defaultSchemaInfo.Database && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(schemaExtractionTasks.Any(t => t.Catalog==defaultSchemaInfo.Database && t.Schema==nodeConfig.SchemaMapping.Apply("Model2")), Is.True); + Assert.That(schemaExtractionTasks.Any(t => t.Catalog == defaultSchemaInfo.Database && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(schemaExtractionTasks.Any(t => t.Catalog == defaultSchemaInfo.Database && t.Schema == nodeConfig.SchemaMapping.Apply(Schema2)), Is.True); var fullName = mappingResolver.GetNodeName("dummy", "SchemaName", "Table1"); Assert.That(fullName, Is.EqualTo("SchemaName:Table1")); - fullName = mappingResolver.GetNodeName("dummy", "Model1", "Table1"); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1") + ":" + "Table1")); + fullName = mappingResolver.GetNodeName("dummy", Schema1, "Table1"); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1) + ":Table1")); - var table = extractionResult.Catalogs.First().Schemas["Model1"].Tables["TestEntity1"]; + var table = extractionResult.Catalogs.First().Schemas[Schema1].Tables["TestEntity1"]; fullName = mappingResolver.GetNodeName(table); - Assert.That(fullName, Is.EqualTo("Model1" + ":" + "TestEntity1")); + Assert.That(fullName, Is.EqualTo(Schema1 + ":TestEntity1")); - table = extractionResult.Catalogs.First().Schemas["Model2"].Tables["TestEntity4"]; + table = extractionResult.Catalogs.First().Schemas[Schema2].Tables["TestEntity4"]; fullName = mappingResolver.GetNodeName(table); - Assert.That(fullName, Is.EqualTo("Model2" + ":" + "TestEntity4")); + Assert.That(fullName, Is.EqualTo(Schema2 + ":TestEntity4")); - var typeInfo = domain.Model.Types[typeof (model.Part1.TestEntity1)]; + var typeInfo = domain.Model.Types[typeof(model.Part1.TestEntity1)]; fullName = mappingResolver.GetNodeName(typeInfo); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1") + ":" + "TestEntity1")); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1) + ":TestEntity1")); var resolveResult = mappingResolver.Resolve(extractionResult, fullName); - Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo("Model1")); + Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo(Schema1)); var schema = mappingResolver.ResolveSchema(extractionResult, typeInfo.MappingDatabase, typeInfo.MappingSchema); - Assert.That(schema.GetNameInternal(), Is.EqualTo("Model1")); + Assert.That(schema.GetNameInternal(), Is.EqualTo(Schema1)); - typeInfo = domain.Model.Types[typeof (model.Part4.TestEntity4)]; + typeInfo = domain.Model.Types[typeof(model.Part4.TestEntity4)]; fullName = mappingResolver.GetNodeName(typeInfo); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model2") + ":" + "TestEntity4")); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema2) + ":TestEntity4")); resolveResult = mappingResolver.Resolve(extractionResult, fullName); - Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo("Model2")); + Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo(Schema2)); schema = mappingResolver.ResolveSchema(extractionResult, typeInfo.MappingDatabase, typeInfo.MappingSchema); - Assert.That(schema.GetNameInternal(), Is.EqualTo("Model2")); + Assert.That(schema.GetNameInternal(), Is.EqualTo(Schema2)); var sequence = typeInfo.Hierarchy.Key.Sequence; fullName = mappingResolver.GetNodeName(sequence); - Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply("Model1") + ":" + sequence.MappingName)); + Assert.That(fullName, Is.EqualTo(nodeConfig.SchemaMapping.Apply(Schema1) + ":" + sequence.MappingName)); resolveResult = mappingResolver.Resolve(extractionResult, fullName); - Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo("Model1")); + Assert.That(resolveResult.Schema.GetNameInternal(), Is.EqualTo(Schema1)); } } } @@ -369,27 +384,27 @@ public void MultidatebaseMappingResolverTest() domainConfiguration.Types.Register(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace); domainConfiguration.Types.Register(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace); - domainConfiguration.Databases.Add("DO-Tests-1"); - domainConfiguration.Databases.Add("DO-Tests-2"); + _ = domainConfiguration.Databases.Add(DOTests1Db); + _ = domainConfiguration.Databases.Add(DOTests2Db); - domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model2"); - domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model1"); - domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model2"); + domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema2); + domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema2); - domainConfiguration.DefaultDatabase = "DO-Tests-1"; - domainConfiguration.DefaultSchema = "Model1"; + domainConfiguration.DefaultDatabase = DOTests1Db; + domainConfiguration.DefaultSchema = Schema1; var nodeConfiguration = new NodeConfiguration("Additional"); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - nodeConfiguration.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - nodeConfiguration.SchemaMapping.Add("Model1", "Model3"); - nodeConfiguration.SchemaMapping.Add("Model2", "Model4"); + nodeConfiguration.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + nodeConfiguration.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + nodeConfiguration.SchemaMapping.Add(Schema1, Schema3); + nodeConfiguration.SchemaMapping.Add(Schema2, Schema4); using (var domain = Domain.Build(domainConfiguration)) { - domain.StorageNodeManager.AddNode(nodeConfiguration); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration); var defaultNodeConfig = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId).Configuration; var additionalNodeConfig = domain.StorageNodeManager.GetNode("Additional").Configuration; @@ -406,27 +421,30 @@ public void MultidatebaseMappingResolverTest() var additionalMappingResolver = MappingResolver.Create(domainConfiguration, additionalNodeConfig, defaultSchemaInfo); Assert.That(additionalMappingResolver, Is.InstanceOf()); - var resolverPerNodeMap = new Dictionary {{defaultNodeConfig, defaultMappingResolver}, {additionalNodeConfig, additionalMappingResolver}}; + var resolverPerNodeMap = new Dictionary { + { defaultNodeConfig, defaultMappingResolver }, + { additionalNodeConfig, additionalMappingResolver } + }; - var baseDb1 = "DO-Tests-1"; - var baseDb2 = "DO-Tests-2"; - var baseSch1 = "Model1"; - var baseSch2 = "Model2"; + var baseDb1 = DOTests1Db; + var baseDb2 = DOTests2Db; + var baseSch1 = Schema1; + var baseSch2 = Schema2; foreach (var pair in resolverPerNodeMap) { var nodeConfig = pair.Key; var resolver = pair.Value; var tasks = resolver.GetSchemaTasks(); Assert.That(tasks.Count(), Is.EqualTo(4)); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-1") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-1") && t.Schema==nodeConfig.SchemaMapping.Apply("Model2")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-2") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-2") && t.Schema==nodeConfig.SchemaMapping.Apply("Model2")), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests1Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests1Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema2)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests2Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests2Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema2)), Is.True); tasks = resolver.GetMetadataTasks(); Assert.That(tasks.Count(), Is.EqualTo(2)); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-1") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-2") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests1Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests2Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); SchemaExtractionResult extractionResult; using (var connection = driver.CreateConnection()) { @@ -440,7 +458,7 @@ public void MultidatebaseMappingResolverTest() var expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb1); var expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch1); - fullName = resolver.GetNodeName("DO-Tests-1", "Model1", "TestEntity1"); + fullName = resolver.GetNodeName(DOTests1Db, Schema1, "TestEntity1"); Assert.That(fullName, Is.EqualTo(string.Format("{0}:{1}:TestEntity1", expectedDatabase, expectedSchema))); var table = extractionResult @@ -469,7 +487,7 @@ public void MultidatebaseMappingResolverTest() fullName = resolver.GetNodeName(table); Assert.That(fullName, Is.EqualTo(string.Format("{0}:{1}:TestEntity3", expectedDatabase, expectedSchema))); - var typeinfo = domain.Model.Types[typeof (model.Part1.TestEntity1)]; + var typeinfo = domain.Model.Types[typeof(model.Part1.TestEntity1)]; expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb1); expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch1); fullName = resolver.GetNodeName(typeinfo); @@ -483,7 +501,7 @@ public void MultidatebaseMappingResolverTest() Assert.That(schema.GetNameInternal(), Is.EqualTo(expectedSchema)); Assert.That(schema.Catalog.GetNameInternal(), Is.EqualTo(expectedDatabase)); - typeinfo = domain.Model.Types[typeof (model.Part2.TestEntity2)]; + typeinfo = domain.Model.Types[typeof(model.Part2.TestEntity2)]; expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb1); expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch2); fullName = resolver.GetNodeName(typeinfo); @@ -498,7 +516,7 @@ public void MultidatebaseMappingResolverTest() Assert.That(schema.Catalog.GetNameInternal(), Is.EqualTo(expectedDatabase)); - typeinfo = domain.Model.Types[typeof (model.Part3.TestEntity3)]; + typeinfo = domain.Model.Types[typeof(model.Part3.TestEntity3)]; expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb2); expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch1); fullName = resolver.GetNodeName(typeinfo); @@ -527,27 +545,27 @@ public void MultidatabaseMappingResolverOnSharedSchemaTest() domainConfiguration.Types.Register(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace); domainConfiguration.Types.Register(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace); - domainConfiguration.Databases.Add("DO-Tests-1"); - domainConfiguration.Databases.Add("DO-Tests-2"); + _ = domainConfiguration.Databases.Add(DOTests1Db); + _ = domainConfiguration.Databases.Add(DOTests2Db); - domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model2"); - domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model1"); - domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model2"); + domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema2); + domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema2); - domainConfiguration.DefaultDatabase = "DO-Tests-1"; - domainConfiguration.DefaultSchema = "Model1"; + domainConfiguration.DefaultDatabase = DOTests1Db; + domainConfiguration.DefaultSchema = Schema1; var nodeConfiguration = new NodeConfiguration("Additional"); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - nodeConfiguration.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - nodeConfiguration.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - nodeConfiguration.SchemaMapping.Add("Model1", "Model3"); - nodeConfiguration.SchemaMapping.Add("Model2", "Model4"); + nodeConfiguration.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + nodeConfiguration.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + nodeConfiguration.SchemaMapping.Add(Schema1, Schema3); + nodeConfiguration.SchemaMapping.Add(Schema2, Schema4); using (var domain = Domain.Build(domainConfiguration)) { - domain.StorageNodeManager.AddNode(nodeConfiguration); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration); var defaultNodeConfig = domain.StorageNodeManager.GetNode(WellKnown.DefaultNodeId).Configuration; var additionalNodeConfig = domain.StorageNodeManager.GetNode("Additional").Configuration; @@ -569,29 +587,32 @@ public void MultidatabaseMappingResolverOnSharedSchemaTest() connection.Open(); extractionResult = new SchemaExtractionResult(driver.Extract(connection, defaultMappingResolver.GetSchemaTasks())); } - extractionResult.MakeShared(); + _ = extractionResult.MakeShared(); - var resolverPerNodeMap = new Dictionary {{defaultNodeConfig, defaultMappingResolver}, {additionalNodeConfig, additionalMappingResolver}}; + var resolverPerNodeMap = new Dictionary { + { defaultNodeConfig, defaultMappingResolver }, + { additionalNodeConfig, additionalMappingResolver } + }; - var baseDb1 = "DO-Tests-1"; - var baseDb2 = "DO-Tests-2"; - var baseSch1 = "Model1"; - var baseSch2 = "Model2"; + var baseDb1 = DOTests1Db; + var baseDb2 = DOTests2Db; + var baseSch1 = Schema1; + var baseSch2 = Schema2; foreach (var pair in resolverPerNodeMap) { var nodeConfig = pair.Key; var resolver = pair.Value; var tasks = resolver.GetSchemaTasks(); Assert.That(tasks.Count(), Is.EqualTo(4)); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-1") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-1") && t.Schema==nodeConfig.SchemaMapping.Apply("Model2")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-2") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-2") && t.Schema==nodeConfig.SchemaMapping.Apply("Model2")), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests1Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests1Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema2)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests2Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests2Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema2)), Is.True); tasks = resolver.GetMetadataTasks(); Assert.That(tasks.Count(), Is.EqualTo(2)); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-1") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); - Assert.That(tasks.Any(t => t.Catalog==nodeConfig.DatabaseMapping.Apply("DO-Tests-2") && t.Schema==nodeConfig.SchemaMapping.Apply("Model1")), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests1Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); + Assert.That(tasks.Any(t => t.Catalog == nodeConfig.DatabaseMapping.Apply(DOTests2Db) && t.Schema == nodeConfig.SchemaMapping.Apply(Schema1)), Is.True); var fullName = resolver.GetNodeName("TestDb", "TestSchema", "TestEntity1"); @@ -600,7 +621,7 @@ public void MultidatabaseMappingResolverOnSharedSchemaTest() var expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb1); var expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch1); - fullName = resolver.GetNodeName("DO-Tests-1", "Model1", "TestEntity1"); + fullName = resolver.GetNodeName(DOTests1Db, Schema1, "TestEntity1"); Assert.That(fullName, Is.EqualTo(string.Format("{0}:{1}:TestEntity1", expectedDatabase, expectedSchema))); @@ -631,7 +652,7 @@ public void MultidatabaseMappingResolverOnSharedSchemaTest() fullName = resolver.GetNodeName(table); Assert.That(fullName, Is.EqualTo(string.Format("{0}:{1}:TestEntity3", expectedDatabase, expectedSchema))); - var typeinfo = domain.Model.Types[typeof (model.Part1.TestEntity1)]; + var typeinfo = domain.Model.Types[typeof(model.Part1.TestEntity1)]; expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb1); expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch1); fullName = resolver.GetNodeName(typeinfo); @@ -647,7 +668,7 @@ public void MultidatabaseMappingResolverOnSharedSchemaTest() Assert.That(schema.GetNameInternal(), Is.EqualTo(expectedSchema)); Assert.That(schema.Catalog.GetNameInternal(), Is.EqualTo(expectedDatabase)); - typeinfo = domain.Model.Types[typeof (model.Part2.TestEntity2)]; + typeinfo = domain.Model.Types[typeof(model.Part2.TestEntity2)]; expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb1); expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch2); fullName = resolver.GetNodeName(typeinfo); @@ -664,7 +685,7 @@ public void MultidatabaseMappingResolverOnSharedSchemaTest() Assert.That(schema.Catalog.GetNameInternal(), Is.EqualTo(expectedDatabase)); - typeinfo = domain.Model.Types[typeof (model.Part3.TestEntity3)]; + typeinfo = domain.Model.Types[typeof(model.Part3.TestEntity3)]; expectedDatabase = nodeConfig.DatabaseMapping.Apply(baseDb2); expectedSchema = nodeConfig.SchemaMapping.Apply(baseSch1); fullName = resolver.GetNodeName(typeinfo); diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultidatabaseTest.cs index 7291b6588b..9e476e104e 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultidatabaseTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.04.03 @@ -13,6 +13,16 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.MetadataUpdate { public class MultidatabaseTest : SimpleTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { base.CheckRequirements(); @@ -22,34 +32,33 @@ protected override void CheckRequirements() protected override void ApplyCustomSettingsToInitialConfiguration(DomainConfiguration domainConfiguration) { base.ApplyCustomSettingsToInitialConfiguration(domainConfiguration); - domainConfiguration.DefaultSchema = "Model1"; - domainConfiguration.DefaultDatabase = "DO-Tests-1"; - - domainConfiguration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model3"); - domainConfiguration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model3"); + ApplyCustomDomainSettings(domainConfiguration); } protected override void ApplyCustomSettingsToTestConfiguration(DomainConfiguration domainConfiguration) { base.ApplyCustomSettingsToTestConfiguration(domainConfiguration); - domainConfiguration.DefaultSchema = "Model1"; - domainConfiguration.DefaultDatabase = "DO-Tests-1"; - domainConfiguration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model3"); - domainConfiguration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model3"); + ApplyCustomDomainSettings(domainConfiguration); + } + + private static void ApplyCustomDomainSettings(DomainConfiguration domainConfiguration) + { + domainConfiguration.DefaultSchema = Schema1; + domainConfiguration.DefaultDatabase = DOTests1Db; + domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema3); + domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema3); } protected override IEnumerable GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - additional.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; + additional.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + additional.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultischemaTest.cs index 29c0369967..e61dfde09c 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/MetadataUpdate/MultischemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.04.03 @@ -13,6 +13,11 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.MetadataUpdate { public class MultischemaTest : SimpleTest { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { base.CheckRequirements(); @@ -22,29 +27,30 @@ protected override void CheckRequirements() protected override void ApplyCustomSettingsToInitialConfiguration(DomainConfiguration domainConfiguration) { base.ApplyCustomSettingsToInitialConfiguration(domainConfiguration); - domainConfiguration.DefaultSchema = "Model1"; - domainConfiguration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).ToSchema("Model3"); - domainConfiguration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).ToSchema("Model3"); + ApplyCustomDomainSettings(domainConfiguration); } protected override void ApplyCustomSettingsToTestConfiguration(DomainConfiguration domainConfiguration) { base.ApplyCustomSettingsToTestConfiguration(domainConfiguration); - domainConfiguration.DefaultSchema = "Model1"; - domainConfiguration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - domainConfiguration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).ToSchema("Model3"); - domainConfiguration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).ToSchema("Model3"); + ApplyCustomDomainSettings(domainConfiguration); + } + + private static void ApplyCustomDomainSettings(DomainConfiguration domainConfiguration) + { + domainConfiguration.DefaultSchema = Schema1; + domainConfiguration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + domainConfiguration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema(Schema3); + domainConfiguration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema(Schema3); } protected override IEnumerable GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs index f9c83d2ea4..465d683dc9 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.29 @@ -107,10 +107,7 @@ public class NewTestEntity4 : Entity public class CustomUpgradeHandler : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnSchemaReady() { @@ -120,18 +117,21 @@ public override void OnSchemaReady() var session = Session.Current; var queryBuilder = session.Services.Get(); if (UpgradeContext.NodeConfiguration.UpgradeMode.IsMultistage()) { - if (UpgradeContext.Stage==UpgradeStage.Upgrading) + if (UpgradeContext.Stage == UpgradeStage.Upgrading) { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveNormalCatalogName, ResolveNormalSchemaName); - else + } + else { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } else { - if (UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.LegacySkip || - UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.Skip) { + if (UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.LegacySkip || + UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.Skip) { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveSharedCatalogName, ResolveSharedSchemaName); } - else + else { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } } @@ -143,18 +143,21 @@ public override void OnBeforeExecuteActions(UpgradeActionSequence actions) var session = Session.Current; var queryBuilder = session.Services.Get(); if (UpgradeContext.NodeConfiguration.UpgradeMode.IsMultistage()) { - if (UpgradeContext.Stage==UpgradeStage.Upgrading) + if (UpgradeContext.Stage == UpgradeStage.Upgrading) { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveNormalCatalogName, ResolveNormalSchemaName); - else + } + else { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } else { - if (UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.LegacySkip || - UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.Skip) { + if (UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.LegacySkip || + UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.Skip) { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveSharedCatalogName, ResolveSharedSchemaName); } - else + else { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } } @@ -179,18 +182,21 @@ public override void OnStage() var queryBuilder = session.Services.Get(); if (UpgradeContext.NodeConfiguration.UpgradeMode.IsMultistage()) { - if (UpgradeContext.Stage==UpgradeStage.Upgrading) + if (UpgradeContext.Stage == UpgradeStage.Upgrading) { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveNormalCatalogName, ResolveNormalSchemaName); - else + } + else { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveSharedCatalogName, ResolveSharedSchemaName); + } } else { - if (UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.LegacySkip || - UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.Skip) { + if (UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.LegacySkip || + UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.Skip) { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveSharedCatalogName, ResolveSharedSchemaName); } - else + else { ValidateSchemaBasedQueriesWork(queryBuilder, ResolveSharedCatalogName, ResolveSharedSchemaName); + } } ValidateNodeBasedQueriesWork(queryBuilder, session); @@ -198,7 +204,7 @@ public override void OnStage() private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Session session) { - var typeinfo = session.Domain.Model.Types[typeof (Part1.TestEntity1)]; + var typeinfo = session.Domain.Model.Types[typeof(Part1.TestEntity1)]; var testEntity1 = session.StorageNode.Mapping[typeinfo]; var tableRef = SqlDml.TableRef(testEntity1); var select = SqlDml.Select(tableRef); @@ -207,7 +213,7 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se var text = ExecuteScalar(queryBuilder, select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - typeinfo = session.Domain.Model.Types[typeof (Part2.TestEntity2)]; + typeinfo = session.Domain.Model.Types[typeof(Part2.TestEntity2)]; var testEntity2 = session.StorageNode.Mapping[typeinfo]; tableRef = SqlDml.TableRef(testEntity2); select = SqlDml.Select(tableRef); @@ -216,7 +222,7 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se text = ExecuteScalar(queryBuilder, select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - typeinfo = session.Domain.Model.Types[typeof (Part3.TestEntity3)]; + typeinfo = session.Domain.Model.Types[typeof(Part3.TestEntity3)]; var testEntity3 = session.StorageNode.Mapping[typeinfo]; tableRef = SqlDml.TableRef(testEntity3); select = SqlDml.Select(tableRef); @@ -225,7 +231,7 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se text = ExecuteScalar(queryBuilder, select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - typeinfo = session.Domain.Model.Types[typeof (Part4.TestEntity4)]; + typeinfo = session.Domain.Model.Types[typeof(Part4.TestEntity4)]; var testEntity4 = session.StorageNode.Mapping[typeinfo]; tableRef = SqlDml.TableRef(testEntity4); select = SqlDml.Select(tableRef); @@ -235,13 +241,16 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); } - private void ValidateSchemaBasedQueriesWork(Services.QueryBuilder queryBuilder, Func catalogNameResolver, Func schemaNameResolver) + private void ValidateSchemaBasedQueriesWork( + Services.QueryBuilder queryBuilder, + Func catalogNameResolver, + Func schemaNameResolver) { var storageSchema = GetStorageSchema(); var databaseMap = GetDatabaseMap(); var schemaMap = GetSchemaMap(); - var type = typeof (Part1.TestEntity1); + var type = typeof(Part1.TestEntity1); var catalogName = catalogNameResolver(databaseMap[type]); var schemaName = schemaNameResolver(schemaMap[type]); var testEntity1 = storageSchema.Catalogs[catalogName].Schemas[schemaName].Tables["TestEntity1"]; @@ -252,7 +261,7 @@ private void ValidateSchemaBasedQueriesWork(Services.QueryBuilder queryBuilder, var text = ExecuteScalar(queryBuilder, select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - type = typeof (Part2.TestEntity2); + type = typeof(Part2.TestEntity2); catalogName = catalogNameResolver(databaseMap[type]); schemaName = schemaNameResolver(schemaMap[type]); var testEntity2 = storageSchema.Catalogs[catalogName].Schemas[schemaName].Tables["TestEntity2"]; @@ -263,7 +272,7 @@ private void ValidateSchemaBasedQueriesWork(Services.QueryBuilder queryBuilder, text = ExecuteScalar(queryBuilder, select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - type = typeof (Part3.TestEntity3); + type = typeof(Part3.TestEntity3); catalogName = catalogNameResolver(databaseMap[type]); schemaName = schemaNameResolver(schemaMap[type]); var testEntity3 = storageSchema.Catalogs[catalogName].Schemas[schemaName].Tables["TestEntity3"]; @@ -274,7 +283,7 @@ private void ValidateSchemaBasedQueriesWork(Services.QueryBuilder queryBuilder, text = ExecuteScalar(queryBuilder, select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - type = typeof (Part4.TestEntity4); + type = typeof(Part4.TestEntity4); catalogName = catalogNameResolver(databaseMap[type]); schemaName = schemaNameResolver(schemaMap[type]); var testEntity4 = storageSchema.Catalogs[catalogName].Schemas[schemaName].Tables["TestEntity4"]; @@ -286,25 +295,15 @@ private void ValidateSchemaBasedQueriesWork(Services.QueryBuilder queryBuilder, Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); } - private string ResolveSharedCatalogName(string baseName) - { - return baseName; - } + private string ResolveSharedCatalogName(string baseName) => baseName; - private string ResolveNormalCatalogName(string baseName) - { - return UpgradeContext.NodeConfiguration.DatabaseMapping.Apply(baseName); - } + private string ResolveNormalCatalogName(string baseName) => + UpgradeContext.NodeConfiguration.DatabaseMapping.Apply(baseName); - private string ResolveSharedSchemaName(string baseName) - { - return baseName; - } + private string ResolveSharedSchemaName(string baseName) => baseName; - private string ResolveNormalSchemaName(string baseName) - { - return UpgradeContext.NodeConfiguration.SchemaMapping.Apply(baseName); - } + private string ResolveNormalSchemaName(string baseName) => + UpgradeContext.NodeConfiguration.SchemaMapping.Apply(baseName); private SchemaExtractionResult GetStorageSchema() { @@ -325,16 +324,16 @@ private IDictionary GetDatabaseMap() var configuration = UpgradeContext.Configuration; var dictionary = new Dictionary(); if (configuration.IsMultidatabase) { - dictionary.Add(typeof(Part1.TestEntity1), "DO-Tests-1"); - dictionary.Add(typeof(Part2.TestEntity2), "DO-Tests-1"); - dictionary.Add(typeof(Part3.TestEntity3), "DO-Tests-2"); - dictionary.Add(typeof(Part4.TestEntity4), "DO-Tests-2"); + dictionary.Add(typeof(Part1.TestEntity1), WellKnownDatabases.MultiDatabase.AdditionalDb1); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownDatabases.MultiDatabase.AdditionalDb1); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownDatabases.MultiDatabase.AdditionalDb2); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.AdditionalDb2); } else { - dictionary.Add(typeof(Part1.TestEntity1), "DO-Tests"); - dictionary.Add(typeof(Part2.TestEntity2), "DO-Tests"); - dictionary.Add(typeof(Part3.TestEntity3), "DO-Tests"); - dictionary.Add(typeof(Part4.TestEntity4), "DO-Tests"); + dictionary.Add(typeof(Part1.TestEntity1), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.MainDb); } return dictionary; } @@ -343,23 +342,17 @@ private IDictionary GetSchemaMap() { var configuration = UpgradeContext.Configuration; var dictionary = new Dictionary(); - if (configuration.IsMultidatabase) { - dictionary.Add(typeof(Part1.TestEntity1), "Model1"); - dictionary.Add(typeof(Part2.TestEntity2), "Model1"); - dictionary.Add(typeof(Part3.TestEntity3), "Model3"); - dictionary.Add(typeof(Part4.TestEntity4), "Model3"); - } - else if (configuration.IsMultischema) { - dictionary.Add(typeof(Part1.TestEntity1), "Model1"); - dictionary.Add(typeof(Part2.TestEntity2), "Model1"); - dictionary.Add(typeof(Part3.TestEntity3), "Model3"); - dictionary.Add(typeof(Part4.TestEntity4), "Model3"); + if (configuration.IsMultidatabase || configuration.IsMultischema) { + dictionary.Add(typeof(Part1.TestEntity1), WellKnownSchemas.Schema1); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownSchemas.Schema1); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownSchemas.Schema3); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.Schema3); } else { - dictionary.Add(typeof(Part1.TestEntity1), "dbo"); - dictionary.Add(typeof(Part2.TestEntity2), "dbo"); - dictionary.Add(typeof(Part3.TestEntity3), "dbo"); - dictionary.Add(typeof(Part4.TestEntity4), "dbo"); + dictionary.Add(typeof(Part1.TestEntity1), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.SqlServerDefaultSchema); } return dictionary; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultidatabaseTest.cs index 1d44105bf6..0a301578ad 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultidatabaseTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.30 @@ -12,6 +12,16 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.QueryBuilder { public class MultidatabaseTest : SimpleTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { base.CheckRequirements(); @@ -21,23 +31,23 @@ protected override void CheckRequirements() protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof (Model.Part1.TestEntity1).Assembly, typeof (Model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof (Model.Part2.TestEntity2).Assembly, typeof (Model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof (Model.Part3.TestEntity3).Assembly, typeof (Model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model3"); - configuration.MappingRules.Map(typeof (Model.Part4.TestEntity4).Assembly, typeof (Model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model3"); + configuration.DefaultSchema = Schema1; + configuration.DefaultDatabase = DOTests1Db; + configuration.MappingRules.Map(typeof(Model.Part1.TestEntity1).Assembly, typeof(Model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(Model.Part2.TestEntity2).Assembly, typeof(Model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(Model.Part3.TestEntity3).Assembly, typeof(Model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema3); + configuration.MappingRules.Map(typeof(Model.Part4.TestEntity4).Assembly, typeof(Model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema3); return configuration; } protected override List GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - additional.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; + additional.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + additional.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultischemaTest.cs index d3effe3cc9..9a874257e4 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/MultischemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.30 @@ -12,6 +12,11 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.QueryBuilder { public class MultischemaTest : SimpleTest { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { base.CheckRequirements(); @@ -21,20 +26,20 @@ protected override void CheckRequirements() protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof (Model.Part1.TestEntity1).Assembly, typeof (Model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (Model.Part2.TestEntity2).Assembly, typeof (Model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (Model.Part3.TestEntity3).Assembly, typeof (Model.Part3.TestEntity3).Namespace).ToSchema("Model3"); - configuration.MappingRules.Map(typeof (Model.Part4.TestEntity4).Assembly, typeof (Model.Part4.TestEntity4).Namespace).ToSchema("Model3"); + configuration.DefaultSchema = Schema1; + configuration.MappingRules.Map(typeof(Model.Part1.TestEntity1).Assembly, typeof(Model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(Model.Part2.TestEntity2).Assembly, typeof(Model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(Model.Part3.TestEntity3).Assembly, typeof(Model.Part3.TestEntity3).Namespace).ToSchema(Schema3); + configuration.MappingRules.Map(typeof(Model.Part4.TestEntity4).Assembly, typeof(Model.Part4.TestEntity4).Namespace).ToSchema(Schema3); return configuration; } protected override List GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultidatabaseTest.cs index f26af4770e..6a94db6b80 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultidatabaseTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.29 @@ -13,6 +13,16 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.Requests { public class MultidatabaseTest : SimpleTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { base.CheckRequirements(); @@ -22,23 +32,23 @@ protected override void CheckRequirements() protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof (Model.Part1.TestEntity1).Assembly, typeof (Model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof (Model.Part2.TestEntity2).Assembly, typeof (Model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof (Model.Part3.TestEntity3).Assembly, typeof (Model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model3"); - configuration.MappingRules.Map(typeof (Model.Part4.TestEntity4).Assembly, typeof (Model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model3"); + configuration.DefaultSchema = Schema1; + configuration.DefaultDatabase = DOTests1Db; + configuration.MappingRules.Map(typeof(Model.Part1.TestEntity1).Assembly, typeof(Model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(Model.Part2.TestEntity2).Assembly, typeof(Model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(Model.Part3.TestEntity3).Assembly, typeof(Model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema3); + configuration.MappingRules.Map(typeof(Model.Part4.TestEntity4).Assembly, typeof(Model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema3); return configuration; } protected override List GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-2"); - additional.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; + additional.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + additional.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultischemaTest.cs index 8d72acf168..e8f589d06b 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/MultischemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.29 @@ -12,6 +12,11 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.Requests { public class MultischemaTest : SimpleTest { + private const string Model1 = WellKnownSchemas.Schema1; + private const string Model2 = WellKnownSchemas.Schema2; + private const string Model3 = WellKnownSchemas.Schema3; + private const string Model4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { base.CheckRequirements(); @@ -21,20 +26,20 @@ protected override void CheckRequirements() protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof (Model.Part1.TestEntity1).Assembly, typeof (Model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (Model.Part2.TestEntity2).Assembly, typeof (Model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (Model.Part3.TestEntity3).Assembly, typeof (Model.Part3.TestEntity3).Namespace).ToSchema("Model3"); - configuration.MappingRules.Map(typeof (Model.Part4.TestEntity4).Assembly, typeof (Model.Part4.TestEntity4).Namespace).ToSchema("Model3"); + configuration.DefaultSchema = Model1; + configuration.MappingRules.Map(typeof(Model.Part1.TestEntity1).Assembly, typeof(Model.Part1.TestEntity1).Namespace).ToSchema(Model1); + configuration.MappingRules.Map(typeof(Model.Part2.TestEntity2).Assembly, typeof(Model.Part2.TestEntity2).Namespace).ToSchema(Model1); + configuration.MappingRules.Map(typeof(Model.Part3.TestEntity3).Assembly, typeof(Model.Part3.TestEntity3).Namespace).ToSchema(Model3); + configuration.MappingRules.Map(typeof(Model.Part4.TestEntity4).Assembly, typeof(Model.Part4.TestEntity4).Namespace).ToSchema(Model3); return configuration; } protected override List GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; + additional.SchemaMapping.Add(Model1, Model2); + additional.SchemaMapping.Add(Model3, Model4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs index ad8b5097e0..279290aa30 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.28 @@ -107,10 +107,7 @@ public class NewTestEntity4 : Entity public class CustomUpgradeHandler : UpgradeHandler { - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + public override bool CanUpgradeFrom(string oldVersion) => true; public override void OnSchemaReady() { @@ -121,18 +118,21 @@ public override void OnSchemaReady() var sqlExecutor = session.Services.Get(); if (UpgradeContext.NodeConfiguration.UpgradeMode.IsMultistage()) { - if (UpgradeContext.Stage==UpgradeStage.Upgrading) + if (UpgradeContext.Stage == UpgradeStage.Upgrading) { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveNormalCatalogName, ResolveNormalSchemaName); - else + } + else { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } else { - if (UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.LegacySkip || - UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.Skip) { + if (UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.LegacySkip || + UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.Skip) { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveSharedCatalogName, ResolveSharedSchemaName); } - else + else { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } } @@ -146,18 +146,21 @@ public override void OnBeforeExecuteActions(UpgradeActionSequence actions) var sqlExecutor = session.Services.Get(); if (UpgradeContext.NodeConfiguration.UpgradeMode.IsMultistage()) { - if (UpgradeContext.Stage==UpgradeStage.Upgrading) + if (UpgradeContext.Stage == UpgradeStage.Upgrading) { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveNormalCatalogName, ResolveNormalSchemaName); - else + } + else { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } else { - if (UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.LegacySkip || - UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.Skip) { + if (UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.LegacySkip || + UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.Skip) { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveSharedCatalogName, ResolveSharedSchemaName); } - else + else { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveNormalCatalogName, ResolveNormalSchemaName); + } } } @@ -182,18 +185,21 @@ public override void OnStage() var sqlExecutor = session.Services.Get(); if (UpgradeContext.NodeConfiguration.UpgradeMode.IsMultistage()) { - if (UpgradeContext.Stage==UpgradeStage.Upgrading) + if (UpgradeContext.Stage == UpgradeStage.Upgrading) { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveNormalCatalogName, ResolveNormalSchemaName); - else + } + else { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveSharedCatalogName, ResolveSharedSchemaName); + } } else { - if (UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.LegacySkip || - UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.Skip) { + if (UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.LegacySkip || + UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.Skip) { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveSharedCatalogName, ResolveSharedSchemaName); } - else + else { ValidateSchemaBasedQueriesWork(sqlExecutor, ResolveSharedCatalogName, ResolveSharedSchemaName); + } } ValidateNodeBasedQueriesWork(sqlExecutor, session); @@ -201,7 +207,7 @@ public override void OnStage() private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session session) { - var typeinfo = session.Domain.Model.Types[typeof (Part1.TestEntity1)]; + var typeinfo = session.Domain.Model.Types[typeof(Part1.TestEntity1)]; var testEntity1 = session.StorageNode.Mapping[typeinfo]; var tableRef = SqlDml.TableRef(testEntity1); var select = SqlDml.Select(tableRef); @@ -210,7 +216,7 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess var text = sqlExecutor.ExecuteScalar(select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - typeinfo = session.Domain.Model.Types[typeof (Part2.TestEntity2)]; + typeinfo = session.Domain.Model.Types[typeof(Part2.TestEntity2)]; var testEntity2 = session.StorageNode.Mapping[typeinfo]; tableRef = SqlDml.TableRef(testEntity2); select = SqlDml.Select(tableRef); @@ -219,7 +225,7 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess text = sqlExecutor.ExecuteScalar(select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - typeinfo = session.Domain.Model.Types[typeof (Part3.TestEntity3)]; + typeinfo = session.Domain.Model.Types[typeof(Part3.TestEntity3)]; var testEntity3 = session.StorageNode.Mapping[typeinfo]; tableRef = SqlDml.TableRef(testEntity3); select = SqlDml.Select(tableRef); @@ -228,7 +234,7 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess text = sqlExecutor.ExecuteScalar(select); Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - typeinfo = session.Domain.Model.Types[typeof (Part4.TestEntity4)]; + typeinfo = session.Domain.Model.Types[typeof(Part4.TestEntity4)]; var testEntity4 = session.StorageNode.Mapping[typeinfo]; tableRef = SqlDml.TableRef(testEntity4); select = SqlDml.Select(tableRef); @@ -238,13 +244,16 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); } - private void ValidateSchemaBasedQueriesWork(ISqlExecutor sqlExecutor, Func catalogNameResolver, Func schemaNameResolver) + private void ValidateSchemaBasedQueriesWork( + ISqlExecutor sqlExecutor, + Func catalogNameResolver, + Func schemaNameResolver) { var storageSchema = GetStorageSchema(); var databaseMap = GetDatabaseMap(); var schemaMap = GetSchemaMap(); - var type = typeof (Part1.TestEntity1); + var type = typeof(Part1.TestEntity1); var catalogName = catalogNameResolver(databaseMap[type]); var schemaName = schemaNameResolver(schemaMap[type]); var testEntity1 = storageSchema.Catalogs[catalogName].Schemas[schemaName].Tables["TestEntity1"]; @@ -255,7 +264,7 @@ private void ValidateSchemaBasedQueriesWork(ISqlExecutor sqlExecutor, Func baseName; - private string ResolveNormalCatalogName(string baseName) - { - return UpgradeContext.NodeConfiguration.DatabaseMapping.Apply(baseName); - } + private string ResolveNormalCatalogName(string baseName) => + UpgradeContext.NodeConfiguration.DatabaseMapping.Apply(baseName); - private string ResolveSharedSchemaName(string baseName) - { - return baseName; - } + private string ResolveSharedSchemaName(string baseName) => baseName; - private string ResolveNormalSchemaName(string baseName) - { - return UpgradeContext.NodeConfiguration.SchemaMapping.Apply(baseName); - } + private string ResolveNormalSchemaName(string baseName) => + UpgradeContext.NodeConfiguration.SchemaMapping.Apply(baseName); private SchemaExtractionResult GetStorageSchema() { @@ -320,16 +319,16 @@ private IDictionary GetDatabaseMap() var configuration = UpgradeContext.Configuration; var dictionary = new Dictionary(); if (configuration.IsMultidatabase) { - dictionary.Add(typeof (Part1.TestEntity1), "DO-Tests-1"); - dictionary.Add(typeof (Part2.TestEntity2), "DO-Tests-1"); - dictionary.Add(typeof (Part3.TestEntity3), "DO-Tests-2"); - dictionary.Add(typeof (Part4.TestEntity4), "DO-Tests-2"); + dictionary.Add(typeof(Part1.TestEntity1), WellKnownDatabases.MultiDatabase.AdditionalDb1); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownDatabases.MultiDatabase.AdditionalDb1); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownDatabases.MultiDatabase.AdditionalDb2); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.AdditionalDb2); } else { - dictionary.Add(typeof (Part1.TestEntity1), "DO-Tests"); - dictionary.Add(typeof (Part2.TestEntity2), "DO-Tests"); - dictionary.Add(typeof (Part3.TestEntity3), "DO-Tests"); - dictionary.Add(typeof (Part4.TestEntity4), "DO-Tests"); + dictionary.Add(typeof(Part1.TestEntity1), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.MainDb); } return dictionary; } @@ -338,23 +337,17 @@ private IDictionary GetSchemaMap() { var configuration = UpgradeContext.Configuration; var dictionary = new Dictionary(); - if (configuration.IsMultidatabase) { - dictionary.Add(typeof (Part1.TestEntity1), "Model1"); - dictionary.Add(typeof (Part2.TestEntity2), "Model1"); - dictionary.Add(typeof (Part3.TestEntity3), "Model3"); - dictionary.Add(typeof (Part4.TestEntity4), "Model3"); - } - else if (configuration.IsMultischema) { - dictionary.Add(typeof (Part1.TestEntity1), "Model1"); - dictionary.Add(typeof (Part2.TestEntity2), "Model1"); - dictionary.Add(typeof (Part3.TestEntity3), "Model3"); - dictionary.Add(typeof (Part4.TestEntity4), "Model3"); + if (configuration.IsMultidatabase || configuration.IsMultischema) { + dictionary.Add(typeof(Part1.TestEntity1), WellKnownSchemas.Schema1); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownSchemas.Schema1); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownSchemas.Schema3); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.Schema3); } else { - dictionary.Add(typeof (Part1.TestEntity1), "dbo"); - dictionary.Add(typeof (Part2.TestEntity2), "dbo"); - dictionary.Add(typeof (Part3.TestEntity3), "dbo"); - dictionary.Add(typeof (Part4.TestEntity4), "dbo"); + dictionary.Add(typeof(Part1.TestEntity1), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part2.TestEntity2), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part3.TestEntity3), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.SqlServerDefaultSchema); } return dictionary; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultidatabaseTest.cs index 1d858c3d4f..082d6be2ad 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultidatabaseTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.28 @@ -13,6 +13,16 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.SqlExecutor { public class MultidatabaseTest : SimpleTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { Require.AllFeaturesSupported(ProviderFeatures.Multidatabase); @@ -21,23 +31,23 @@ protected override void CheckRequirements() protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.DefaultDatabase = "DO-Tests-1"; - configuration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model3"); - configuration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model3"); + configuration.DefaultSchema = Schema1; + configuration.DefaultDatabase = DOTests1Db; + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema3); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema3); return configuration; } protected override List GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - additional.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; + additional.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + additional.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs index 4ff4f13f66..5859d4365f 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.28 @@ -13,6 +13,11 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.SqlExecutor { public class MultischemaTest : SimpleTest { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string Schema3 = WellKnownSchemas.Schema3; + private const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { base.CheckRequirements(); @@ -22,11 +27,11 @@ protected override void CheckRequirements() protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.MappingRules.Map(typeof (model.Part1.TestEntity1).Assembly, typeof (model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (model.Part2.TestEntity2).Assembly, typeof (model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof (model.Part3.TestEntity3).Assembly, typeof (model.Part3.TestEntity3).Namespace).ToSchema("Model3"); - configuration.MappingRules.Map(typeof (model.Part4.TestEntity4).Assembly, typeof (model.Part4.TestEntity4).Namespace).ToSchema("Model3"); + configuration.DefaultSchema = Schema1; + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema(Schema3); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema(Schema3); return configuration; } @@ -34,8 +39,8 @@ protected override List GetNodes(DomainUpgradeMode upgradeMod { var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; - additional.SchemaMapping.Add("Model1", "Model2"); - additional.SchemaMapping.Add("Model3", "Model4"); + additional.SchemaMapping.Add(Schema1, Schema2); + additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/StorageNodeBuildingTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/StorageNodeBuildingTest.cs index cf2e3c383c..b0ac8be297 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/StorageNodeBuildingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/StorageNodeBuildingTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017-2020 Xtensive LLC. +// Copyright (C) 2017-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -69,6 +69,9 @@ public override void OnComplete(Domain domain) public class StorageNodeBuildingTest : AutoBuildTest { + private const string Schema1 = WellKnownSchemas.Schema1; + private const string Schema2 = WellKnownSchemas.Schema2; + private const string MainNodeId = WellKnown.DefaultNodeId; private const string AdditionalNodeId = "Additional"; @@ -339,7 +342,7 @@ private void ValidateUpgradingMapping(Domain domain, ModelMapping mapping, bool private Dictionary BuildNodeToSchemaMap() { return ProviderInfo.Supports(ProviderFeatures.Multischema) - ? new Dictionary {{MainNodeId, "Model1"}, {AdditionalNodeId, "Model2"}} + ? new Dictionary { { MainNodeId, Schema1 }, { AdditionalNodeId, Schema2 } } : new Dictionary(); } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultidatabaseTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultidatabaseTest.cs index 780080c446..6f138c7493 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultidatabaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultidatabaseTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.03 @@ -12,6 +12,11 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.TemporaryTableManager { public sealed class MultidatabaseTest : MultischemaTest { + private const string DOTests1Db = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string DOTests2Db = WellKnownDatabases.MultiDatabase.AdditionalDb2; + private const string DOTests3Db = WellKnownDatabases.MultiDatabase.AdditionalDb3; + private const string DOTests4Db = WellKnownDatabases.MultiDatabase.AdditionalDb4; + protected override void CheckRequirements() { Require.AllFeaturesSupported(ProviderFeatures.Multidatabase); @@ -20,13 +25,13 @@ protected override void CheckRequirements() protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; - configuration.DefaultDatabase = "DO-Tests-1"; + configuration.DefaultSchema = Schema1; + configuration.DefaultDatabase = DOTests1Db; - configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To("DO-Tests-1", "Model1"); - configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To("DO-Tests-1", "Model2"); - configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To("DO-Tests-2", "Model1"); - configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To("DO-Tests-2", "Model2"); + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).To(DOTests1Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).To(DOTests1Db, Schema2); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).To(DOTests2Db, Schema1); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).To(DOTests2Db, Schema2); return configuration; } @@ -34,10 +39,10 @@ protected override DomainConfiguration GetDomainConfiguration() protected override NodeConfiguration GetNodeConfiguration() { var nodeConfiguration = new NodeConfiguration("Additional"); - nodeConfiguration.DatabaseMapping.Add("DO-Tests-1", "DO-Tests-3"); - nodeConfiguration.DatabaseMapping.Add("DO-Tests-2", "DO-Tests-4"); - nodeConfiguration.SchemaMapping.Add("Model1", "Model3"); - nodeConfiguration.SchemaMapping.Add("Model2", "Model4"); + nodeConfiguration.DatabaseMapping.Add(DOTests1Db, DOTests3Db); + nodeConfiguration.DatabaseMapping.Add(DOTests2Db, DOTests4Db); + nodeConfiguration.SchemaMapping.Add(Schema1, Schema3); + nodeConfiguration.SchemaMapping.Add(Schema2, Schema4); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; return nodeConfiguration; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultischemaTest.cs index 9798079539..f185934f3a 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/TemporaryTableManager/MultischemaTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.03 @@ -13,6 +13,11 @@ namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing.TemporaryTableManager { public class MultischemaTest : SimpleTest { + protected const string Schema1 = WellKnownSchemas.Schema1; + protected const string Schema2 = WellKnownSchemas.Schema2; + protected const string Schema3 = WellKnownSchemas.Schema3; + protected const string Schema4 = WellKnownSchemas.Schema4; + protected override void CheckRequirements() { Require.AllFeaturesSupported(ProviderFeatures.Multischema); @@ -22,8 +27,7 @@ protected override Domain BuildReferenceDomain() { var configuration = GetDomainConfiguration(); var domain = Domain.Build(configuration); - domain.StorageNodeManager.AddNode(GetNodeConfiguration()); - + _ = domain.StorageNodeManager.AddNode(GetNodeConfiguration()); return domain; } @@ -32,20 +36,19 @@ protected override Domain BuildTestDomain() var configuration = GetDomainConfiguration(); configuration.ShareStorageSchemaOverNodes = true; var domain = Domain.Build(configuration); - domain.StorageNodeManager.AddNode(GetNodeConfiguration()); - + _ = domain.StorageNodeManager.AddNode(GetNodeConfiguration()); return domain; } protected override DomainConfiguration GetDomainConfiguration() { var configuration = base.GetDomainConfiguration(); - configuration.DefaultSchema = "Model1"; + configuration.DefaultSchema = Schema1; - configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema("Model1"); - configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema("Model2"); - configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema("Model2"); + configuration.MappingRules.Map(typeof(model.Part1.TestEntity1).Assembly, typeof(model.Part1.TestEntity1).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part2.TestEntity2).Assembly, typeof(model.Part2.TestEntity2).Namespace).ToSchema(Schema1); + configuration.MappingRules.Map(typeof(model.Part3.TestEntity3).Assembly, typeof(model.Part3.TestEntity3).Namespace).ToSchema(Schema2); + configuration.MappingRules.Map(typeof(model.Part4.TestEntity4).Assembly, typeof(model.Part4.TestEntity4).Namespace).ToSchema(Schema2); return configuration; } @@ -59,8 +62,8 @@ protected override IEnumerable GetNodeIdentifiers() protected virtual NodeConfiguration GetNodeConfiguration() { var nodeConfiguration = new NodeConfiguration("Additional"); - nodeConfiguration.SchemaMapping.Add("Model1", "Model3"); - nodeConfiguration.SchemaMapping.Add("Model2", "Model4"); + nodeConfiguration.SchemaMapping.Add(Schema1, Schema3); + nodeConfiguration.SchemaMapping.Add(Schema2, Schema4); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; return nodeConfiguration; } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeContextTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeContextTest.cs index ec3c717d40..4b6641557f 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeContextTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeContextTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2018 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2018-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2018.09.27 @@ -25,23 +25,12 @@ public class TestEntity : Entity public class AccessGatherer { - private Dictionary stagesAccess = new Dictionary(); + private readonly Dictionary stagesAccess = new Dictionary(); - public ProviderInfo this[MethodInfo method] - { - get - { - ProviderInfo result; - if (stagesAccess.TryGetValue(method, out result)) - return result; - return null; - } - } + public ProviderInfo this[MethodInfo method] => + stagesAccess.TryGetValue(method, out var result) ? result : null; - public void Add(MethodBase method, ProviderInfo givenProvider) - { - stagesAccess.Add(method, givenProvider); - } + public void Add(MethodBase method, ProviderInfo givenProvider) => stagesAccess.Add(method, givenProvider); } public class CustomUpgrader : UpgradeHandler @@ -160,36 +149,40 @@ public sealed class UpgradeContextTest private MethodInfo[] upgraderMethods; [OneTimeSetUp] - public void TestFixture() - { - upgraderMethods = UpgraderMethods(); - } + public void TestFixture() => upgraderMethods = UpgraderMethods(); [Test] public void AccessToProviderInfoOnDomainBuildingTest() { Domain domain; - using (domain = BuildDomain(DomainUpgradeMode.Recreate)) + using (domain = BuildDomain(DomainUpgradeMode.Recreate)) { ValidateAccess(domain.Extensions.Get()); + } - using (domain = BuildDomain(DomainUpgradeMode.Perform)) + using (domain = BuildDomain(DomainUpgradeMode.Perform)) { ValidateAccess(domain.Extensions.Get()); + } - using (domain = BuildDomain(DomainUpgradeMode.PerformSafely)) + using (domain = BuildDomain(DomainUpgradeMode.PerformSafely)) { ValidateAccess(domain.Extensions.Get()); + } - using (domain = BuildDomain(DomainUpgradeMode.Validate)) + using (domain = BuildDomain(DomainUpgradeMode.Validate)) { ValidateAccess(domain.Extensions.Get()); + } - using (domain = BuildDomain(DomainUpgradeMode.Skip)) + using (domain = BuildDomain(DomainUpgradeMode.Skip)) { ValidateAccess(domain.Extensions.Get()); + } - using (domain = BuildDomain(DomainUpgradeMode.LegacyValidate)) + using (domain = BuildDomain(DomainUpgradeMode.LegacyValidate)) { ValidateAccess(domain.Extensions.Get()); + } - using (domain = BuildDomain(DomainUpgradeMode.LegacySkip)) + using (domain = BuildDomain(DomainUpgradeMode.LegacySkip)) { ValidateAccess(domain.Extensions.Get()); + } } [Test] @@ -201,37 +194,37 @@ public void AccessToProviderInfoOnStorageNodeBuildingTest() AddStorageNode(domain, DomainUpgradeMode.Recreate); var gatherer = domain.Extensions.Get(); ValidateAccess(gatherer); - domain.StorageNodeManager.RemoveNode(additionalNodeName); + _ = domain.StorageNodeManager.RemoveNode(additionalNodeName); AddStorageNode(domain, DomainUpgradeMode.Perform); gatherer = domain.Extensions.Get(); ValidateAccess(gatherer); - domain.StorageNodeManager.RemoveNode(additionalNodeName); + _ = domain.StorageNodeManager.RemoveNode(additionalNodeName); AddStorageNode(domain, DomainUpgradeMode.PerformSafely); gatherer = domain.Extensions.Get(); ValidateAccess(gatherer); - domain.StorageNodeManager.RemoveNode(additionalNodeName); + _ = domain.StorageNodeManager.RemoveNode(additionalNodeName); AddStorageNode(domain, DomainUpgradeMode.Validate); gatherer = domain.Extensions.Get(); ValidateAccess(gatherer); - domain.StorageNodeManager.RemoveNode(additionalNodeName); + _ = domain.StorageNodeManager.RemoveNode(additionalNodeName); AddStorageNode(domain, DomainUpgradeMode.Skip); gatherer = domain.Extensions.Get(); ValidateAccess(gatherer); - domain.StorageNodeManager.RemoveNode(additionalNodeName); + _ = domain.StorageNodeManager.RemoveNode(additionalNodeName); AddStorageNode(domain, DomainUpgradeMode.LegacySkip); gatherer = domain.Extensions.Get(); ValidateAccess(gatherer); - domain.StorageNodeManager.RemoveNode(additionalNodeName); + _ = domain.StorageNodeManager.RemoveNode(additionalNodeName); AddStorageNode(domain, DomainUpgradeMode.LegacyValidate); gatherer = domain.Extensions.Get(); ValidateAccess(gatherer); - domain.StorageNodeManager.RemoveNode(additionalNodeName); + _ = domain.StorageNodeManager.RemoveNode(additionalNodeName); } } @@ -241,8 +234,9 @@ private void ValidateAccess(AccessGatherer accessGatherer) foreach (var upgraderMethod in upgraderMethods) { var tested = accessGatherer[upgraderMethod]; - if (tested==null) + if (tested == null) { continue; + } Assert.That(tested.ConstantPrimaryIndexName, Is.EqualTo(expected.ConstantPrimaryIndexName)); Assert.That(tested.DefaultDatabase, Is.EqualTo(expected.DefaultDatabase)); @@ -252,8 +246,9 @@ private void ValidateAccess(AccessGatherer accessGatherer) Assert.That(tested.ProviderName, Is.EqualTo(expected.ProviderName)); Assert.That(tested.StorageVersion, Is.EqualTo(expected.StorageVersion)); - foreach (var supportedType in tested.SupportedTypes) + foreach (var supportedType in tested.SupportedTypes) { Assert.That(expected.SupportedTypes.Contains(supportedType), Is.True); + } } } @@ -261,8 +256,8 @@ private Domain BuildDomain(DomainUpgradeMode upgradeMode) { var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = upgradeMode; - configuration.Types.Register(typeof (TestEntity)); - configuration.Types.Register(typeof (CustomUpgrader)); + configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(CustomUpgrader)); return Domain.Build(configuration); } @@ -271,9 +266,9 @@ private Domain BuildMultischemaDomain(DomainUpgradeMode upgradeMode) { var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = upgradeMode; - configuration.Types.Register(typeof (TestEntity)); - configuration.Types.Register(typeof (CustomUpgrader)); - configuration.DefaultSchema = "dbo"; + configuration.Types.Register(typeof(TestEntity)); + configuration.Types.Register(typeof(CustomUpgrader)); + configuration.DefaultSchema = WellKnownSchemas.SqlServerDefaultSchema; return Domain.Build(configuration); } @@ -281,23 +276,22 @@ private Domain BuildMultischemaDomain(DomainUpgradeMode upgradeMode) private void AddStorageNode(Domain domain, DomainUpgradeMode upgradeMode) { var nodeConfiguration = new NodeConfiguration(additionalNodeName); - nodeConfiguration.SchemaMapping.Add("dbo", "Model1"); + nodeConfiguration.SchemaMapping.Add(WellKnownSchemas.SqlServerDefaultSchema, WellKnownSchemas.Schema1); nodeConfiguration.UpgradeMode = upgradeMode; - domain.StorageNodeManager.AddNode(nodeConfiguration); + _ = domain.StorageNodeManager.AddNode(nodeConfiguration); } private MethodInfo[] UpgraderMethods() { - var upgrader = typeof (CustomUpgrader); + var upgrader = typeof(CustomUpgrader); - var publicMethods = + var publicMethods = upgrader.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); var protectedMethods = upgrader.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); return publicMethods.Union(protectedMethods).ToArray(); } - } } From 01c668ecbcf417ce1e3eeac024fdc1abed1c177c Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 29 Apr 2021 15:04:57 +0500 Subject: [PATCH 50/71] Fixed incorrect database setup appeared in 'd384205' --- .../Issues/IssueJira0537_DropDefaultConstraintBugTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs index a8165ba33b..90493603cd 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0537_DropDefaultConstraintBugTest.cs @@ -275,7 +275,7 @@ namespace Xtensive.Orm.Tests.Issues public class IssueJira0537_DropDefaultConstraintBugTest : AutoBuildTest { private const string Database1Name = WellKnownDatabases.MultiDatabase.AdditionalDb1; - private const string Database2Name = WellKnownDatabases.MultiDatabase.AdditionalDb1; + private const string Database2Name = WellKnownDatabases.MultiDatabase.AdditionalDb2; private const string CoreAlias = "core"; private const string WmsAlias = "wms"; private const string SpecialSchemaAlias = WellKnownSchemas.SqlServerDefaultSchema; From 687d18bbe92b63e03681a1ea4aae9e29ffe7f5cb Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 30 Apr 2021 09:32:26 +0500 Subject: [PATCH 51/71] Oracle v11 and newer: No schema name convertion to Upper case Don't know whethere it should be for all the versions so left them as they were. The v11 does not require shemas to be upper case for sure --- .../Sql.Drivers.Oracle/v09/Extractor.cs | 11 ++++++++--- .../Sql.Drivers.Oracle/v11/Extractor.cs | 2 ++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Extractor.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Extractor.cs index dadb3b0346..c95b6564f9 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Extractor.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Extractor.cs @@ -45,7 +45,7 @@ public override Schema ExtractSchema(string catalogName, string schemaName) { targetSchemes.Clear(); theCatalog = new Catalog(catalogName); - var targetSchema = schemaName.ToUpperInvariant(); + var targetSchema = ToUpperInvariantIfNeeded(schemaName); targetSchemes.Add(targetSchema); RegisterReplacements(replacementsRegistry); @@ -60,7 +60,7 @@ public override Catalog ExtractSchemes(string catalogName, string[] schemaNames) theCatalog = new Catalog(catalogName); targetSchemes.Clear(); foreach (var schemaName in schemaNames) { - var targetSchema = schemaName.ToUpperInvariant(); + var targetSchema = ToUpperInvariantIfNeeded(schemaName); targetSchemes.Add(targetSchema); } @@ -71,6 +71,11 @@ public override Catalog ExtractSchemes(string catalogName, string[] schemaNames) return theCatalog; } + protected virtual string ToUpperInvariantIfNeeded(string schemaName) + { + return schemaName.ToUpperInvariant(); + } + private void ExtractCatalogContents() { ExtractTables(); @@ -92,7 +97,7 @@ private void ExtractSchemas() while (reader.Read()) theCatalog.CreateSchema(reader.GetString(0)); // choosing the default schema - var defaultSchemaName = Driver.CoreServerInfo.DefaultSchemaName.ToUpperInvariant(); + var defaultSchemaName = ToUpperInvariantIfNeeded(Driver.CoreServerInfo.DefaultSchemaName).ToUpperInvariant(); var defaultSchema = theCatalog.Schemas[defaultSchemaName]; theCatalog.DefaultSchema = defaultSchema; } diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Extractor.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Extractor.cs index 3b8a63753c..79ae90d7d7 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Extractor.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Extractor.cs @@ -13,6 +13,8 @@ internal class Extractor : v10.Extractor { // Constructors + protected override string ToUpperInvariantIfNeeded(string schemaName) => schemaName; + public Extractor(SqlDriver driver) : base(driver) { From dc569c2cb0dfa4909443a72320e404349ecd3eb5 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 30 Apr 2021 16:23:50 +0500 Subject: [PATCH 52/71] Oracle: Attempt to fix transaction serialization error --- .../Sql.Drivers.Oracle/v11/Translator.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs index 9e13782bac..5368bce28b 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs @@ -6,11 +6,32 @@ using System; using Xtensive.Sql.Compiler; +using Xtensive.Sql.Ddl; namespace Xtensive.Sql.Drivers.Oracle.v11 { internal class Translator : v10.Translator { + //so called INITRANS value + protected const int TableTransactionalParallelismLevel = 3; + protected const int IndexTransactionalParallelismLevel = 3; + + public override string Translate(SqlCompilerContext context, SqlCreateTable node, CreateTableSection section) + { + if (section == CreateTableSection.TableElementsExit) + return $") INITRANS {TableTransactionalParallelismLevel} "; + return base.Translate(context, node, section); + } + + public override string Translate(SqlCompilerContext context, SqlCreateIndex node, CreateIndexSection section) + { + if (section == CreateIndexSection.ColumnsExit) + return $") INITRANS {IndexTransactionalParallelismLevel}"; + //CreateIndexSection.ColumnsExit: + //return ")" + return base.Translate(context, node, section); + } + public override string Translate(SqlValueType type) { // we need to explicitly specify maximum interval precision From e0b2103db9abce0acbcfbecd880c095888bcafd0 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 4 May 2021 11:05:36 +0500 Subject: [PATCH 53/71] Even more parallel transactions allowed for Oracle Tables and Indexes --- Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs index 5368bce28b..0636341df4 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs @@ -13,8 +13,8 @@ namespace Xtensive.Sql.Drivers.Oracle.v11 internal class Translator : v10.Translator { //so called INITRANS value - protected const int TableTransactionalParallelismLevel = 3; - protected const int IndexTransactionalParallelismLevel = 3; + protected const int TableTransactionalParallelismLevel = 7; + protected const int IndexTransactionalParallelismLevel = 7; public override string Translate(SqlCompilerContext context, SqlCreateTable node, CreateTableSection section) { From 766d45fa057b0b08c5465c6c85fdb54f7fe9db4e Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 4 May 2021 19:41:09 +0500 Subject: [PATCH 54/71] Apply Oracle behavior workarounds to some tests --- .../Storage/Multinode/QueryCachingTest.cs | 97 +++++++++-------- .../SchemaSharing/EntityManipulation/Model.cs | 22 +++- .../SimpleEntityManipulationTest.cs | 91 +++++++++------- .../Upgrade/SchemaSharing/IgnoreRulesTest.cs | 30 +++++- .../SchemaSharing/QueryBuilder/Model.cs | 78 +++++++++++--- .../SchemaSharing/QueryBuilder/SimpleTest.cs | 16 +-- .../Upgrade/SchemaSharing/Requests/Model.cs | 100 +++++++++++------- .../SchemaSharing/Requests/SimpleTest.cs | 16 +-- .../SchemaSharing/SqlExecutor/Model.cs | 78 +++++++++++--- .../SqlExecutor/MultischemaTest.cs | 4 +- .../SchemaSharing/SqlExecutor/SimpleTest.cs | 27 ++--- 11 files changed, 374 insertions(+), 185 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs index f2f01899b0..446764b19c 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multinode/QueryCachingTest.cs @@ -92,9 +92,9 @@ namespace Xtensive.Orm.Tests.Storage.Multinode { public sealed class QueryCachingTest : MultinodeTest { - private const string dbo = WellKnownSchemas.SqlServerDefaultSchema; - private const string Schema1 = WellKnownSchemas.Schema1; - private const string Schema2 = WellKnownSchemas.Schema2; + private const string DefaultSchema = WellKnownSchemas.Schema1; + private const string Schema1 = WellKnownSchemas.Schema2; + private const string Schema2 = WellKnownSchemas.Schema3; private readonly object SimpleQueryKey = new object(); private readonly object FilterByIdQueryKey = new object(); @@ -113,7 +113,7 @@ protected override DomainConfiguration BuildConfiguration() var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(BaseTestEntity).Assembly, typeof(BaseTestEntity).Namespace); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.DefaultSchema = dbo; + configuration.DefaultSchema = DefaultSchema; return configuration; } @@ -121,13 +121,13 @@ protected override void PopulateNodes() { CustomUpgradeHandler.CurrentNodeId = TestNodeId2; var nodeConfiguration = new NodeConfiguration(TestNodeId2); - nodeConfiguration.SchemaMapping.Add(dbo, Schema1); + nodeConfiguration.SchemaMapping.Add(DefaultSchema, Schema1); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; _ = Domain.StorageNodeManager.AddNode(nodeConfiguration); CustomUpgradeHandler.CurrentNodeId = TestNodeId3; nodeConfiguration = new NodeConfiguration(TestNodeId3); - nodeConfiguration.SchemaMapping.Add(dbo, Schema2); + nodeConfiguration.SchemaMapping.Add(DefaultSchema, Schema2); nodeConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; _ = Domain.StorageNodeManager.AddNode(nodeConfiguration); } @@ -142,68 +142,70 @@ protected override void PopulateData() using (var tx = session.OpenTransaction()) { #region Entity creation - _ = new BaseTestEntity(session) { BaseName = "A", BaseOwnerNodeId = nodeId }; + var nodeIdName = string.IsNullOrEmpty(nodeId) ? "" : nodeId; + + _ = new BaseTestEntity(session) { BaseName = "A", BaseOwnerNodeId = nodeIdName }; _ = new MiddleTestEntity(session) { BaseName = "AA", MiddleName = "AAM", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName }; _ = new LeafTestEntity(session) { BaseName = "AAA", MiddleName = "AAAM", LeafName = "AAAL", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId, - LeafOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName, + LeafOwnerNodeId = nodeIdName }; - _ = new BaseTestEntity(session) { BaseName = "B", BaseOwnerNodeId = nodeId }; + _ = new BaseTestEntity(session) { BaseName = "B", BaseOwnerNodeId = nodeIdName }; _ = new MiddleTestEntity(session) { BaseName = "BB", MiddleName = "BBM", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName }; _ = new LeafTestEntity(session) { BaseName = "BBB", MiddleName = "BBBM", LeafName = "BBBL", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId, - LeafOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName, + LeafOwnerNodeId = nodeIdName }; - _ = new BaseTestEntity(session) { BaseName = "C", BaseOwnerNodeId = nodeId }; + _ = new BaseTestEntity(session) { BaseName = "C", BaseOwnerNodeId = nodeIdName }; _ = new MiddleTestEntity(session) { BaseName = "CC", MiddleName = "CCM", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName }; _ = new LeafTestEntity(session) { BaseName = "CCC", MiddleName = "CCCM", LeafName = "CCCL", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId, - LeafOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName, + LeafOwnerNodeId = nodeIdName }; - _ = new BaseTestEntity(session) { BaseName = "D", BaseOwnerNodeId = nodeId }; + _ = new BaseTestEntity(session) { BaseName = "D", BaseOwnerNodeId = nodeIdName }; _ = new MiddleTestEntity(session) { BaseName = "DD", MiddleName = "DDM", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName }; _ = new LeafTestEntity(session) { BaseName = "DDD", MiddleName = "DDDM", LeafName = "DDDL", - BaseOwnerNodeId = nodeId, - MiddleOwnerNodeId = nodeId, - LeafOwnerNodeId = nodeId + BaseOwnerNodeId = nodeIdName, + MiddleOwnerNodeId = nodeIdName, + LeafOwnerNodeId = nodeIdName }; #endregion @@ -254,10 +256,11 @@ private void RunTestSimpleQueryTest(string nodeId) using (var session = selectedNode.OpenSession()) using (var tx = session.OpenTransaction()) { var expectedTypeId = GetExpectedTypeId(nodeId); + var nodeIdName = string.IsNullOrEmpty(nodeId) ? "" : nodeId; var allResults = ExecuteSimpleQueryNoCache(session).OrderBy(e => e.TypeId).ToList(); Assert.That(allResults.Count, Is.EqualTo(3)); - Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeId), Is.True); + Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeIdName), Is.True); Assert.That(allResults[0].BaseName, Is.EqualTo("C")); Assert.That(allResults[0].TypeId, Is.EqualTo(expectedTypeId)); Assert.That(allResults[1].BaseName, Is.EqualTo("CC")); @@ -267,18 +270,18 @@ private void RunTestSimpleQueryTest(string nodeId) var middles = allResults.OfType().ToList(); Assert.That(middles.Count, Is.EqualTo(2)); - Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeId), Is.True); + Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeIdName), Is.True); Assert.That(middles[0].MiddleName, Is.EqualTo("CCM")); Assert.That(middles[1].MiddleName, Is.EqualTo("CCCM")); var leafs = middles.OfType().ToList(); Assert.That(leafs.Count, Is.EqualTo(1)); - Assert.That(leafs[0].LeafOwnerNodeId, Is.EqualTo(nodeId)); + Assert.That(leafs[0].LeafOwnerNodeId, Is.EqualTo(nodeIdName)); Assert.That(leafs[0].LeafName, Is.EqualTo("CCCL")); allResults = ExecuteSimpleQueryCaching(session); Assert.That(allResults.Count, Is.EqualTo(3)); - Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeId), Is.True); + Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeIdName), Is.True); Assert.That(allResults[0].BaseName, Is.EqualTo("B")); Assert.That(allResults[0].TypeId, Is.EqualTo(expectedTypeId)); Assert.That(allResults[1].BaseName, Is.EqualTo("BB")); @@ -288,13 +291,13 @@ private void RunTestSimpleQueryTest(string nodeId) middles = allResults.OfType().ToList(); Assert.That(middles.Count, Is.EqualTo(2)); - Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeId), Is.True); + Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeIdName), Is.True); Assert.That(middles[0].MiddleName, Is.EqualTo("BBM")); Assert.That(middles[1].MiddleName, Is.EqualTo("BBBM")); leafs = middles.OfType().ToList(); Assert.That(leafs.Count, Is.EqualTo(1)); - Assert.That(leafs[0].LeafOwnerNodeId, Is.EqualTo(nodeId)); + Assert.That(leafs[0].LeafOwnerNodeId, Is.EqualTo(nodeIdName)); Assert.That(leafs[0].LeafName, Is.EqualTo("BBBL")); } } @@ -305,10 +308,11 @@ private void RunFilterByTypeIdQueryTest(string nodeId) using (var session = selectedNode.OpenSession()) using (var tx = session.OpenTransaction()) { var expectedTypeId = GetExpectedTypeId(nodeId); + var nodeIdName = string.IsNullOrEmpty(nodeId) ? "" : nodeId; var resultWithoutCache = ExecuteFilterByTypeIdNoCache(session, expectedTypeId); Assert.That(resultWithoutCache.Count, Is.EqualTo(4)); - Assert.That(resultWithoutCache.All(e => e.BaseOwnerNodeId == nodeId)); + Assert.That(resultWithoutCache.All(e => e.BaseOwnerNodeId == nodeIdName)); Assert.That(resultWithoutCache.All(e => e.TypeId == expectedTypeId), Is.True); Assert.That(resultWithoutCache.OfType().Count(), Is.EqualTo(4)); Assert.That(resultWithoutCache.OfType().Any(), Is.False); @@ -316,7 +320,7 @@ private void RunFilterByTypeIdQueryTest(string nodeId) resultWithoutCache = ExecuteFilterByTypeIdNoCache(session, expectedTypeId + 1); Assert.That(resultWithoutCache.Count, Is.EqualTo(4)); - Assert.That(resultWithoutCache.All(e => e.BaseOwnerNodeId == nodeId)); + Assert.That(resultWithoutCache.All(e => e.BaseOwnerNodeId == nodeIdName)); Assert.That(resultWithoutCache.All(e => e.TypeId == expectedTypeId + 1), Is.True); Assert.That(resultWithoutCache.OfType().Count(), Is.EqualTo(4)); Assert.That(resultWithoutCache.OfType().Count(), Is.EqualTo(4)); @@ -324,7 +328,7 @@ private void RunFilterByTypeIdQueryTest(string nodeId) resultWithoutCache = ExecuteFilterByTypeIdNoCache(session, expectedTypeId + 2); Assert.That(resultWithoutCache.Count, Is.EqualTo(4)); - Assert.That(resultWithoutCache.All(e => e.BaseOwnerNodeId == nodeId)); + Assert.That(resultWithoutCache.All(e => e.BaseOwnerNodeId == nodeIdName)); Assert.That(resultWithoutCache.All(e => e.TypeId == expectedTypeId + 2), Is.True); Assert.That(resultWithoutCache.OfType().Count(), Is.EqualTo(4)); Assert.That(resultWithoutCache.OfType().Count(), Is.EqualTo(4)); @@ -332,7 +336,7 @@ private void RunFilterByTypeIdQueryTest(string nodeId) var resultWithCache = ExecuteFilterByTypeIdCaching(session, expectedTypeId); Assert.That(resultWithCache.Count, Is.EqualTo(4)); - Assert.That(resultWithCache.All(e => e.BaseOwnerNodeId == nodeId)); + Assert.That(resultWithCache.All(e => e.BaseOwnerNodeId == nodeIdName)); Assert.That(resultWithCache.All(e => e.TypeId == expectedTypeId), Is.True); Assert.That(resultWithCache.OfType().Count(), Is.EqualTo(4)); Assert.That(resultWithCache.OfType().Any(), Is.False); @@ -340,7 +344,7 @@ private void RunFilterByTypeIdQueryTest(string nodeId) resultWithCache = ExecuteFilterByTypeIdCaching(session, expectedTypeId + 1); Assert.That(resultWithCache.Count, Is.EqualTo(4)); - Assert.That(resultWithCache.All(e => e.BaseOwnerNodeId == nodeId)); + Assert.That(resultWithCache.All(e => e.BaseOwnerNodeId == nodeIdName)); Assert.That(resultWithCache.All(e => e.TypeId == expectedTypeId + 1), Is.True); Assert.That(resultWithCache.OfType().Count(), Is.EqualTo(4)); Assert.That(resultWithCache.OfType().Count(), Is.EqualTo(4)); @@ -348,7 +352,7 @@ private void RunFilterByTypeIdQueryTest(string nodeId) resultWithCache = ExecuteFilterByTypeIdCaching(session, expectedTypeId + 2); Assert.That(resultWithCache.Count, Is.EqualTo(4)); - Assert.That(resultWithCache.All(e => e.BaseOwnerNodeId == nodeId)); + Assert.That(resultWithCache.All(e => e.BaseOwnerNodeId == nodeIdName)); Assert.That(resultWithCache.All(e => e.TypeId == expectedTypeId + 2), Is.True); Assert.That(resultWithCache.OfType().Count(), Is.EqualTo(4)); Assert.That(resultWithCache.OfType().Count(), Is.EqualTo(4)); @@ -369,28 +373,29 @@ private void RunFilterBySeveralTypeIdsTest(string nodeId) using (var session = selectedNode.OpenSession()) using (var tx = session.OpenTransaction()) { var expectedTypeId = GetExpectedTypeId(nodeId); + var nodeIdName = string.IsNullOrEmpty(nodeId) ? "" : nodeId; var allResults = ExecuteFilterBySeveralTypeIdsNoCache(session, new[] { expectedTypeId, expectedTypeId + 1 }) .OrderBy(e => e.TypeId) .ToList(); Assert.That(allResults.Count, Is.EqualTo(8)); - Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeId), Is.True); + Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeIdName), Is.True); Assert.That(allResults.Count(e => e.TypeId == expectedTypeId), Is.EqualTo(4)); Assert.That(allResults.Count(e => e.TypeId == expectedTypeId + 1), Is.EqualTo(4)); var middles = allResults.OfType().ToList(); Assert.That(middles.Count, Is.EqualTo(4)); - Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeId), Is.True); + Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeIdName), Is.True); allResults = ExecuteFilterBySeveralTypeIdsCaching(session, new[] { expectedTypeId, expectedTypeId + 1 }); Assert.That(allResults.Count, Is.EqualTo(8)); - Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeId), Is.True); + Assert.That(allResults.All(e => e.BaseOwnerNodeId == nodeIdName), Is.True); Assert.That(allResults.Count(e => e.TypeId == expectedTypeId), Is.EqualTo(4)); Assert.That(allResults.Count(e => e.TypeId == expectedTypeId + 1), Is.EqualTo(4)); middles = allResults.OfType().ToList(); Assert.That(middles.Count, Is.EqualTo(4)); - Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeId), Is.True); + Assert.That(middles.All(e => e.MiddleOwnerNodeId == nodeIdName), Is.True); var unexpectedTypeIds = GetUnexpectedTypeIds(nodeId); allResults = ExecuteFilterBySeveralTypeIdsNoCache(session, unexpectedTypeIds); diff --git a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/Model.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/Model.cs index 617f9ed86a..770455d796 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/Model.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Xtensive LLC. +// Copyright (C) 2017 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexey Kulakov @@ -22,6 +22,11 @@ public class TestEntity1 : Entity [Field] public string SchemaName { get; set; } + + public TestEntity1(Session session) + : base(session) + { + } } } @@ -41,6 +46,11 @@ public class TestEntity2 : Entity [Field] public string SchemaName { get; set; } + + public TestEntity2(Session session) + : base(session) + { + } } } @@ -60,6 +70,11 @@ public class TestEntity3 : Entity [Field] public string SchemaName { get; set; } + + public TestEntity3(Session session) + : base(session) + { + } } } @@ -79,6 +94,11 @@ public class TestEntity4 : Entity [Field] public string SchemaName { get; set; } + + public TestEntity4(Session session) + : base(session) + { + } } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/SimpleEntityManipulationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/SimpleEntityManipulationTest.cs index 2b2ffd2973..e9bf5dd3e2 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/SimpleEntityManipulationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/EntityManipulation/SimpleEntityManipulationTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017-2020 Xtensive LLC. +// Copyright (C) 2017-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -67,7 +67,7 @@ protected void RunTest(DomainUpgradeMode upgradeMode) ApplyCustomSettingsToTestConfiguration(configuration); configuration.UpgradeMode = upgradeMode; configuration.ShareStorageSchemaOverNodes = true; - var initialEntitiesCount = (upgradeMode!=DomainUpgradeMode.Recreate) ? 1 : 0; + var initialEntitiesCount = (upgradeMode != DomainUpgradeMode.Recreate) ? 1 : 0; using (var domain = Domain.Build(configuration)) { var nodes = GetNodes(upgradeMode); @@ -111,22 +111,25 @@ protected void PopulateInitialDataForNodes() using (var transaction = session.OpenTransaction()) { var type = typeof(model.Part1.TestEntity1); var pair = GetDatabaseAndSchemaForType(session, type); - _ = new model.Part1.TestEntity1 { Text = session.StorageNodeId, DatabaseName = pair.First, SchemaName = pair.Second }; + + var storageNodeIdText = GetStorageNodeText(session.StorageNodeId); + + _ = new model.Part1.TestEntity1(session) { Text = storageNodeIdText, DatabaseName = pair.First, SchemaName = pair.Second }; typesMap.Add(type, pair); type = typeof(model.Part2.TestEntity2); pair = GetDatabaseAndSchemaForType(session, typeof(model.Part2.TestEntity2)); - _ = new model.Part2.TestEntity2 { Text = session.StorageNodeId, DatabaseName = pair.First, SchemaName = pair.Second }; + _ = new model.Part2.TestEntity2(session) { Text = storageNodeIdText, DatabaseName = pair.First, SchemaName = pair.Second }; typesMap.Add(type, pair); type = typeof(model.Part3.TestEntity3); pair = GetDatabaseAndSchemaForType(session, typeof(model.Part3.TestEntity3)); - _ = new model.Part3.TestEntity3 { Text = session.StorageNodeId, DatabaseName = pair.First, SchemaName = pair.Second }; + _ = new model.Part3.TestEntity3(session) { Text = storageNodeIdText, DatabaseName = pair.First, SchemaName = pair.Second }; typesMap.Add(type, pair); type = typeof(model.Part4.TestEntity4); pair = GetDatabaseAndSchemaForType(session, typeof(model.Part4.TestEntity4)); - _ = new model.Part4.TestEntity4 { Text = session.StorageNodeId, DatabaseName = pair.First, SchemaName = pair.Second }; + _ = new model.Part4.TestEntity4(session) { Text = storageNodeIdText, DatabaseName = pair.First, SchemaName = pair.Second }; typesMap.Add(type, pair); transaction.Complete(); @@ -139,10 +142,10 @@ protected void PopulateInitialDataForNodes() protected DomainConfiguration BuildConfiguration() { var configuration = DomainConfigurationFactory.Create(); - configuration.Types.Register(typeof (model.Part1.TestEntity1)); - configuration.Types.Register(typeof (model.Part2.TestEntity2)); - configuration.Types.Register(typeof (model.Part3.TestEntity3)); - configuration.Types.Register(typeof (model.Part4.TestEntity4)); + configuration.Types.Register(typeof(model.Part1.TestEntity1)); + configuration.Types.Register(typeof(model.Part2.TestEntity2)); + configuration.Types.Register(typeof(model.Part3.TestEntity3)); + configuration.Types.Register(typeof(model.Part4.TestEntity4)); return configuration; } @@ -185,6 +188,8 @@ private void MainSelectTest(Session session, int initialCountOfEntities) } var storageNodeId = session.StorageNodeId; + var storageNodeIdText = GetStorageNodeText(session.StorageNodeId); + var a = session.Query.All().ToList(); var b = session.Query.All().ToList(); var c = session.Query.All().ToList(); @@ -203,49 +208,51 @@ private void MainSelectTest(Session session, int initialCountOfEntities) } var entity1 = a[0]; - Assert.That(entity1.Text, Is.EqualTo(storageNodeId)); + Assert.That(entity1.Text, Is.EqualTo(storageNodeIdText)); var databaseAndSchema = typesMap[entity1.GetType()]; Assert.That(entity1.DatabaseName, Is.EqualTo(databaseAndSchema.First)); Assert.That(entity1.SchemaName, Is.EqualTo(databaseAndSchema.Second)); Entity entity = session.Query.All() - .FirstOrDefault(e => e.Text == storageNodeId && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); + .FirstOrDefault(e => e.Text == storageNodeIdText && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(entity, Is.Not.Null); var entity2 = b[0]; - Assert.That(b[0].Text, Is.EqualTo(storageNodeId)); + Assert.That(b[0].Text, Is.EqualTo(storageNodeIdText)); databaseAndSchema = typesMap[entity2.GetType()]; Assert.That(entity2.DatabaseName, Is.EqualTo(databaseAndSchema.First)); Assert.That(entity2.SchemaName, Is.EqualTo(databaseAndSchema.Second)); entity = session.Query.All() - .FirstOrDefault(e => e.Text == storageNodeId && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); + .FirstOrDefault(e => e.Text == storageNodeIdText && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(entity, Is.Not.Null); var entity3 = c[0]; - Assert.That(c[0].Text, Is.EqualTo(storageNodeId)); + Assert.That(c[0].Text, Is.EqualTo(storageNodeIdText)); databaseAndSchema = typesMap[entity3.GetType()]; Assert.That(entity3.DatabaseName, Is.EqualTo(databaseAndSchema.First)); Assert.That(entity3.SchemaName, Is.EqualTo(databaseAndSchema.Second)); entity = session.Query.All() - .FirstOrDefault(e => e.Text == storageNodeId && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); + .FirstOrDefault(e => e.Text == storageNodeIdText && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(entity, Is.Not.Null); var entity4 = d[0]; - Assert.That(d[0].Text, Is.EqualTo(storageNodeId)); + Assert.That(d[0].Text, Is.EqualTo(storageNodeIdText)); databaseAndSchema = typesMap[entity4.GetType()]; Assert.That(entity4.DatabaseName, Is.EqualTo(databaseAndSchema.First)); Assert.That(entity4.SchemaName, Is.EqualTo(databaseAndSchema.Second)); entity = session.Query.All() - .FirstOrDefault(e => e.Text == storageNodeId && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); + .FirstOrDefault(e => e.Text == storageNodeIdText && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(entity, Is.Not.Null); } protected virtual void AdditionalSelectTest(Session session, int initialCountOfEntities) { var storageNodeId = session.StorageNodeId; + var storageNodeIdText = GetStorageNodeText(session.StorageNodeId); + if (!map.TryGetValue(storageNodeId, out var typesMap)) { throw new Exception(string.Format("Unknown node {0}. Probably you don't populate data", storageNodeId)); } @@ -255,17 +262,17 @@ protected virtual void AdditionalSelectTest(Session session, int initialCountOfE } var type1BaseQuery = session.Query.All() - .Select(e => new model.TestEntityDTO() {Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName}); + .Select(e => new model.TestEntityDTO() { Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName }); var type2BaseQuery = session.Query.All() - .Select(e => new model.TestEntityDTO() {Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName}); + .Select(e => new model.TestEntityDTO() { Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName }); var type3BaseQuery = session.Query.All() - .Select(e => new model.TestEntityDTO() {Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName}); + .Select(e => new model.TestEntityDTO() { Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName }); var type4BaseQuery = session.Query.All() - .Select(e => new model.TestEntityDTO() {Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName}); + .Select(e => new model.TestEntityDTO() { Id = e.Id, TypeId = e.TypeId, Text = e.Text, DatabaseName = e.DatabaseName, SchemaName = e.SchemaName }); IEnumerable theGreatUnion = null; var result = type1BaseQuery.Union(type2BaseQuery).ToList(); - Assert.That(result.Count, Is.EqualTo(2*initialCountOfEntities)); + Assert.That(result.Count, Is.EqualTo(2 * initialCountOfEntities)); theGreatUnion = result; result = type1BaseQuery.Union(type3BaseQuery).ToList(); @@ -293,19 +300,19 @@ protected virtual void AdditionalSelectTest(Session session, int initialCountOfE var expectedDatabase = databaseAndSchema.First; var expectedSchema = databaseAndSchema.Second; - Assert.That(testEntityDto.Text, Is.EqualTo(session.StorageNodeId)); + Assert.That(testEntityDto.Text, Is.EqualTo(storageNodeIdText)); Assert.That(testEntityDto.DatabaseName, Is.EqualTo(expectedDatabase)); Assert.That(testEntityDto.SchemaName, Is.EqualTo(expectedSchema)); } var pair = typesMap[typeof(model.Part1.TestEntity1)]; - var filteredType1BaseQuery = type1BaseQuery.Where(e => e.Text==storageNodeId && e.DatabaseName==pair.First && e.SchemaName==pair.Second); + var filteredType1BaseQuery = type1BaseQuery.Where(e => e.Text == storageNodeIdText && e.DatabaseName == pair.First && e.SchemaName == pair.Second); pair = typesMap[typeof(model.Part2.TestEntity2)]; - var filteredType2BaseQuery = type1BaseQuery.Where(e => e.Text==storageNodeId && e.DatabaseName==pair.First && e.SchemaName==pair.Second); + var filteredType2BaseQuery = type1BaseQuery.Where(e => e.Text == storageNodeIdText && e.DatabaseName == pair.First && e.SchemaName == pair.Second); pair = typesMap[typeof(model.Part3.TestEntity3)]; - var filteredType3BaseQuery = type1BaseQuery.Where(e => e.Text==storageNodeId && e.DatabaseName==pair.First && e.SchemaName==pair.Second); + var filteredType3BaseQuery = type1BaseQuery.Where(e => e.Text == storageNodeIdText && e.DatabaseName == pair.First && e.SchemaName == pair.Second); pair = typesMap[typeof(model.Part4.TestEntity4)]; - var filteredType4BaseQuery = type1BaseQuery.Where(e => e.Text==storageNodeId && e.DatabaseName==pair.First && e.SchemaName==pair.Second); + var filteredType4BaseQuery = type1BaseQuery.Where(e => e.Text == storageNodeIdText && e.DatabaseName == pair.First && e.SchemaName == pair.Second); result = filteredType1BaseQuery.Union(filteredType2BaseQuery).ToList(); Assert.That(result.Count, Is.EqualTo(2 * initialCountOfEntities)); @@ -329,13 +336,15 @@ protected virtual void AdditionalSelectTest(Session session, int initialCountOfE private Key[] Insert(Session session, int initialCountOfEntities) { var storageNodeId = session.StorageNodeId; + var storageNodeIdText = GetStorageNodeText(session.StorageNodeId); + if (!map.TryGetValue(storageNodeId, out var typesMap)) { throw new Exception(string.Format("Unknown node {0}. Probably you don't populate data", storageNodeId)); } - var text = string.Format("{0}_new", storageNodeId); + var text = string.Format("{0}_new", storageNodeIdText); - var a = new model.Part1.TestEntity1 { Text = text }; + var a = new model.Part1.TestEntity1(session) { Text = text }; var databaseAndSchema = typesMap[a.GetType()]; a.DatabaseName = databaseAndSchema.First; a.SchemaName = databaseAndSchema.Second; @@ -345,7 +354,7 @@ private Key[] Insert(Session session, int initialCountOfEntities) a = session.Query.All().FirstOrDefault(e => e.Text == text && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(a, Is.Not.Null); - var b = new model.Part2.TestEntity2 { Text = text }; + var b = new model.Part2.TestEntity2(session) { Text = text }; databaseAndSchema = typesMap[b.GetType()]; b.DatabaseName = databaseAndSchema.First; b.SchemaName = databaseAndSchema.Second; @@ -355,7 +364,7 @@ private Key[] Insert(Session session, int initialCountOfEntities) b = session.Query.All().FirstOrDefault(e => e.Text == text && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(b, Is.Not.Null); - var c = new model.Part3.TestEntity3 { Text = text }; + var c = new model.Part3.TestEntity3(session) { Text = text }; databaseAndSchema = typesMap[c.GetType()]; c.DatabaseName = databaseAndSchema.First; c.SchemaName = databaseAndSchema.Second; @@ -365,7 +374,7 @@ private Key[] Insert(Session session, int initialCountOfEntities) c = session.Query.All().FirstOrDefault(e => e.Text == text && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(c, Is.Not.Null); - var d = new model.Part4.TestEntity4 { Text = text }; + var d = new model.Part4.TestEntity4(session) { Text = text }; databaseAndSchema = typesMap[d.GetType()]; d.DatabaseName = databaseAndSchema.First; d.SchemaName = databaseAndSchema.Second; @@ -381,12 +390,14 @@ private Key[] Insert(Session session, int initialCountOfEntities) private void Update(Session session, Key[] createdKeys, int initialCountOfEntities) { var storageNodeId = session.StorageNodeId; + var storageNodeIdText = GetStorageNodeText(session.StorageNodeId); + if (!map.TryGetValue(storageNodeId, out var typesMap)) { throw new Exception(string.Format("Unknown node {0}. Probably you don't populate data", storageNodeId)); } - var updatedText = string.Format("{0}_new_updated", storageNodeId); - var text = string.Format("{0}_new", storageNodeId); + var updatedText = string.Format("{0}_new_updated", storageNodeIdText); + var text = string.Format("{0}_new", storageNodeIdText); var databaseAndSchema = typesMap[typeof(model.Part1.TestEntity1)]; var a = session.Query.All().FirstOrDefault(e => e.Key == createdKeys[0] && e.Text == text); @@ -457,12 +468,13 @@ private void Update(Session session, Key[] createdKeys, int initialCountOfEntiti private void Delete(Session session, Key[] createdKeys, int initialCountOfEntities) { var storageNodeId = session.StorageNodeId; + var storageNodeIdText = GetStorageNodeText(session.StorageNodeId); if (!map.TryGetValue(storageNodeId, out var typesMap)) { throw new Exception(string.Format("Unknown node {0}. Probably you don't populate data", storageNodeId)); } - var updatedText = string.Format("{0}_new_updated", storageNodeId); + var updatedText = string.Format("{0}_new_updated", storageNodeIdText); var databaseAndSchema = typesMap[typeof(model.Part1.TestEntity1)]; var a = session.Query.All().FirstOrDefault(e => e.Key == createdKeys[0] && e.Text == updatedText); @@ -529,5 +541,12 @@ private void Delete(Session session, Key[] createdKeys, int initialCountOfEntiti .FirstOrDefault(e => e.Key == createdKeys[3] && e.Text == updatedText && e.DatabaseName == databaseAndSchema.First && e.SchemaName == databaseAndSchema.Second); Assert.That(d, Is.Null); } + + public string GetStorageNodeText(string nodeId) + { + return string.IsNullOrEmpty(nodeId) + ? "" + : nodeId; + } } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs index 5807526541..9c887ab09e 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs @@ -281,7 +281,7 @@ private void ManuallyInsertIgnoredItems(Catalog catalog) } var ignoredTable = schema.CreateTable("HiddenTable"); - var idColumn = ignoredTable.CreateColumn("Id", new SqlValueType(SqlType.Int64)); + var idColumn = ignoredTable.CreateColumn("Id", GetTypeForInteger(SqlType.Int64)); idColumn.IsNullable = false; var name = ignoredTable.CreateColumn("Name", GetTypeForString(255)); name.IsNullable = false; @@ -292,7 +292,7 @@ private void ManuallyInsertIgnoredItems(Catalog catalog) } var notInDomainTable1 = schema.CreateTable("NotInDomain1"); - idColumn = notInDomainTable1.CreateColumn("Id", new SqlValueType(SqlType.Int64)); + idColumn = notInDomainTable1.CreateColumn("Id", GetTypeForInteger(SqlType.Int64)); idColumn.IsNullable = false; name = notInDomainTable1.CreateColumn("Name", GetTypeForString(255)); name.IsNullable = false; @@ -303,7 +303,7 @@ private void ManuallyInsertIgnoredItems(Catalog catalog) } var notInDomainTable2 = schema.CreateTable("NotInDomain2"); - idColumn = notInDomainTable2.CreateColumn("Id", new SqlValueType(SqlType.Int64)); + idColumn = notInDomainTable2.CreateColumn("Id", GetTypeForInteger(SqlType.Int64)); idColumn.IsNullable = false; name = notInDomainTable2.CreateColumn("Name", GetTypeForString(255)); name.IsNullable = false; @@ -314,7 +314,7 @@ private void ManuallyInsertIgnoredItems(Catalog catalog) } var notInDomainTable3 = schema.CreateTable("NotInDomain3"); - idColumn = notInDomainTable3.CreateColumn("Id", new SqlValueType(SqlType.Int64)); + idColumn = notInDomainTable3.CreateColumn("Id", GetTypeForInteger(SqlType.Int64)); idColumn.IsNullable = false; name = notInDomainTable3.CreateColumn("Name", GetTypeForString(255)); name.IsNullable = false; @@ -521,6 +521,28 @@ private IgnoreRuleCollection GetIgnoreRules() private SqlValueType GetTypeForString(int? length) => driver.TypeMappings.Mappings[typeof(string)].MapType(length, null, null); + private SqlValueType GetTypeForInteger(SqlType sqlType) + { + if (!StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Oracle)) { + return new SqlValueType(sqlType); + } + + const int ShortPrecision = 5; + const int IntPrecision = 10; + const int LongPrecision = 20; + + if (sqlType == SqlType.Int16) { + return new SqlValueType(SqlType.Decimal, ShortPrecision, 0); + } + if (sqlType == SqlType.Int32) { + return new SqlValueType(SqlType.Decimal, IntPrecision, 0); + } + if (sqlType == SqlType.Int64) { + return new SqlValueType(SqlType.Decimal, LongPrecision, 0); + } + return new SqlValueType(sqlType); + } + private Dictionary BuildNodeToSchemaMap() { return ProviderInfo.Supports(ProviderFeatures.Multischema) diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs index 465d683dc9..10e7e776cb 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/Model.cs @@ -23,6 +23,11 @@ public class TestEntity1 : Entity [Field] public string Text { get; set; } + + public TestEntity1(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -33,6 +38,11 @@ public class NewTestEntity1 : Entity [Field] public string Text { get; set; } + + public NewTestEntity1(Session session) + : base(session) + { + } } } @@ -46,6 +56,11 @@ public class TestEntity2 : Entity [Field] public string Text { get; set; } + + public TestEntity2(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -56,6 +71,11 @@ public class NewTestEntity2 : Entity [Field] public string Text { get; set; } + + public NewTestEntity2(Session session) + : base(session) + { + } } } @@ -69,6 +89,11 @@ public class TestEntity3 : Entity [Field] public string Text { get; set; } + + public TestEntity3(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -79,6 +104,11 @@ public class NewTestEntity3 : Entity [Field] public string Text { get; set; } + + public NewTestEntity3(Session session) + : base(session) + { + } } } @@ -92,6 +122,11 @@ public class TestEntity4 : Entity [Field] public string Text { get; set; } + + public TestEntity4(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -102,6 +137,11 @@ public class NewTestEntity4 : Entity [Field] public string Text { get; set; } + + public NewTestEntity4(Session session) + : base(session) + { + } } } @@ -204,6 +244,8 @@ public override void OnStage() private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Session session) { + var storageNodeText = TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId); + var typeinfo = session.Domain.Model.Types[typeof(Part1.TestEntity1)]; var testEntity1 = session.StorageNode.Mapping[typeinfo]; var tableRef = SqlDml.TableRef(testEntity1); @@ -211,7 +253,7 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se select.Columns.Add(tableRef["Text"]); var text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); typeinfo = session.Domain.Model.Types[typeof(Part2.TestEntity2)]; var testEntity2 = session.StorageNode.Mapping[typeinfo]; @@ -220,7 +262,7 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se select.Columns.Add(tableRef["Text"]); text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); typeinfo = session.Domain.Model.Types[typeof(Part3.TestEntity3)]; var testEntity3 = session.StorageNode.Mapping[typeinfo]; @@ -229,7 +271,7 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se select.Columns.Add(tableRef["Text"]); text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); typeinfo = session.Domain.Model.Types[typeof(Part4.TestEntity4)]; var testEntity4 = session.StorageNode.Mapping[typeinfo]; @@ -238,7 +280,7 @@ private void ValidateNodeBasedQueriesWork(Services.QueryBuilder queryBuilder, Se select.Columns.Add(tableRef["Text"]); text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); } private void ValidateSchemaBasedQueriesWork( @@ -250,6 +292,8 @@ private void ValidateSchemaBasedQueriesWork( var databaseMap = GetDatabaseMap(); var schemaMap = GetSchemaMap(); + var storageNodeText = TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId); + var type = typeof(Part1.TestEntity1); var catalogName = catalogNameResolver(databaseMap[type]); var schemaName = schemaNameResolver(schemaMap[type]); @@ -259,7 +303,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); var text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); type = typeof(Part2.TestEntity2); catalogName = catalogNameResolver(databaseMap[type]); @@ -270,7 +314,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); type = typeof(Part3.TestEntity3); catalogName = catalogNameResolver(databaseMap[type]); @@ -281,7 +325,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); type = typeof(Part4.TestEntity4); catalogName = catalogNameResolver(databaseMap[type]); @@ -292,7 +336,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); text = ExecuteScalar(queryBuilder, select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); } private string ResolveSharedCatalogName(string baseName) => baseName; @@ -330,10 +374,10 @@ private IDictionary GetDatabaseMap() dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.AdditionalDb2); } else { - dictionary.Add(typeof(Part1.TestEntity1), WellKnownDatabases.MultiDatabase.MainDb); - dictionary.Add(typeof(Part2.TestEntity2), WellKnownDatabases.MultiDatabase.MainDb); - dictionary.Add(typeof(Part3.TestEntity3), WellKnownDatabases.MultiDatabase.MainDb); - dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part1.TestEntity1), UpgradeContext.DefaultSchemaInfo.Database); + dictionary.Add(typeof(Part2.TestEntity2), UpgradeContext.DefaultSchemaInfo.Database); + dictionary.Add(typeof(Part3.TestEntity3), UpgradeContext.DefaultSchemaInfo.Database); + dictionary.Add(typeof(Part4.TestEntity4), UpgradeContext.DefaultSchemaInfo.Database); } return dictionary; } @@ -349,13 +393,15 @@ private IDictionary GetSchemaMap() dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.Schema3); } else { - dictionary.Add(typeof(Part1.TestEntity1), WellKnownSchemas.SqlServerDefaultSchema); - dictionary.Add(typeof(Part2.TestEntity2), WellKnownSchemas.SqlServerDefaultSchema); - dictionary.Add(typeof(Part3.TestEntity3), WellKnownSchemas.SqlServerDefaultSchema); - dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part1.TestEntity1), UpgradeContext.DefaultSchemaInfo.Schema); + dictionary.Add(typeof(Part2.TestEntity2), UpgradeContext.DefaultSchemaInfo.Schema); + dictionary.Add(typeof(Part3.TestEntity3), UpgradeContext.DefaultSchemaInfo.Schema); + dictionary.Add(typeof(Part4.TestEntity4), UpgradeContext.DefaultSchemaInfo.Schema); } return dictionary; } + + private string TryGetStorageNodeText(string nodeId) => string.IsNullOrEmpty(nodeId) ? "" : nodeId; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/SimpleTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/SimpleTest.cs index 2c847cccaf..17c86aefb8 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/SimpleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/QueryBuilder/SimpleTest.cs @@ -17,7 +17,7 @@ public class SimpleTest [OneTimeSetUp] public void TestFixtureSetup() => CheckRequirements(); - protected virtual void CheckRequirements() => Require.ProviderIs(StorageProvider.SqlServer); + protected virtual void CheckRequirements() => Require.ProviderIsNot(StorageProvider.Firebird); [Test] public void PerformSafelyTest() @@ -88,12 +88,16 @@ private void BuildInitialDomain() foreach (var nodeConfiguration in nodes) { var selectedNode = domain.StorageNodeManager.GetNode(nodeConfiguration.NodeId); using (var session = selectedNode.OpenSession()) - using (session.Activate()) using (var transaction = session.OpenTransaction()) { - _ = new model.Part1.TestEntity1 { Text = session.StorageNodeId }; - _ = new model.Part2.TestEntity2 { Text = session.StorageNodeId }; - _ = new model.Part3.TestEntity3 { Text = session.StorageNodeId }; - _ = new model.Part4.TestEntity4 { Text = session.StorageNodeId }; + + var storageNodeIdText = string.IsNullOrEmpty(session.StorageNodeId) + ? "" + : session.StorageNodeId; + + _ = new model.Part1.TestEntity1(session) { Text = storageNodeIdText }; + _ = new model.Part2.TestEntity2(session) { Text = storageNodeIdText }; + _ = new model.Part3.TestEntity3(session) { Text = storageNodeIdText }; + _ = new model.Part4.TestEntity4(session) { Text = storageNodeIdText }; transaction.Complete(); } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/Model.cs index 2e6ce49529..9885b40f5c 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/Model.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2017 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2017-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2017.03.29 @@ -20,6 +20,11 @@ public class TestEntity1 : Entity [Field] public string Text { get; set; } + + public TestEntity1(Session session) + : base(session) + { + } } } @@ -33,6 +38,11 @@ public class TestEntity2 : Entity [Field] public string Text { get; set; } + + public TestEntity2(Session session) + : base(session) + { + } } } @@ -46,6 +56,11 @@ public class TestEntity3 : Entity [Field] public string Text { get; set; } + + public TestEntity3(Session session) + : base(session) + { + } } } @@ -59,6 +74,11 @@ public class TestEntity4 : Entity [Field] public string Text { get; set; } + + public TestEntity4(Session session) + : base(session) + { + } } } @@ -73,10 +93,7 @@ public override bool CanUpgradeFrom(string oldVersion) public override void OnPrepare() { - if (UpgradeContext.NodeConfiguration.UpgradeMode==DomainUpgradeMode.Recreate) - initialCountOfEntities = 0; - else - initialCountOfEntities = 1; + initialCountOfEntities = UpgradeContext.NodeConfiguration.UpgradeMode == DomainUpgradeMode.Recreate ? 0 : 1; } public override void OnUpgrade() @@ -112,104 +129,107 @@ private void Select(Session session) Assert.That(session.Query.All().AsEnumerable().Count(), Is.EqualTo(initialCountOfEntities)); Assert.That(session.Query.All().AsEnumerable().Count(), Is.EqualTo(initialCountOfEntities)); - if (initialCountOfEntities==0) + if (initialCountOfEntities == 0) return; - Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); - Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + var storageNodeText = TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId); + Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(storageNodeText)); + Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(storageNodeText)); + Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(storageNodeText)); + Assert.That(session.Query.All().AsEnumerable().First().Text, Is.EqualTo(storageNodeText)); } private Key[] Insert(Session session) { - var text = string.Format("{0}_during_upgrade", UpgradeContext.NodeConfiguration.NodeId); - var a = new Part1.TestEntity1 {Text = text}; - var b = new Part2.TestEntity2 {Text = text}; - var c = new Part3.TestEntity3 {Text = text}; - var d = new Part4.TestEntity4 {Text = text}; + var text = string.Format("{0}_during_upgrade", TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId)); + var a = new Part1.TestEntity1(session) { Text = text }; + var b = new Part2.TestEntity2(session) { Text = text }; + var c = new Part3.TestEntity3(session) { Text = text }; + var d = new Part4.TestEntity4(session) { Text = text }; session.SaveChanges(); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - a = session.Query.All().Where(e => e.Text==text).FirstOrDefault(); + a = session.Query.All().Where(e => e.Text == text).FirstOrDefault(); Assert.That(a, Is.Not.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - b = session.Query.All().Where(e => e.Text==text).FirstOrDefault(); + b = session.Query.All().Where(e => e.Text == text).FirstOrDefault(); Assert.That(b, Is.Not.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - c = session.Query.All().Where(e => e.Text==text).FirstOrDefault(); + c = session.Query.All().Where(e => e.Text == text).FirstOrDefault(); Assert.That(c, Is.Not.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - d = session.Query.All().Where(e => e.Text==text).FirstOrDefault(); + d = session.Query.All().Where(e => e.Text == text).FirstOrDefault(); Assert.That(d, Is.Not.Null); - return new Key[] {a.Key, b.Key, c.Key, d.Key}; + return new Key[] { a.Key, b.Key, c.Key, d.Key }; } private void Update(Session session, Key[] createdKeys) { - var updatedText = string.Format("{0}_during_upgrade_updated", UpgradeContext.NodeConfiguration.NodeId); + var updatedText = string.Format("{0}_during_upgrade_updated", TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId)); - var a = session.Query.All().Where(e => e.Key==createdKeys[0]).First(); + var a = session.Query.All().Where(e => e.Key == createdKeys[0]).First(); a.Text = updatedText; - var b = session.Query.All().Where(e => e.Key==createdKeys[1]).First(); + var b = session.Query.All().Where(e => e.Key == createdKeys[1]).First(); b.Text = updatedText; - var c = session.Query.All().Where(e => e.Key==createdKeys[2]).First(); + var c = session.Query.All().Where(e => e.Key == createdKeys[2]).First(); c.Text = updatedText; - var d = session.Query.All().Where(e => e.Key==createdKeys[3]).First(); + var d = session.Query.All().Where(e => e.Key == createdKeys[3]).First(); d.Text = updatedText; session.SaveChanges(); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - a = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + a = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(a, Is.Not.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - b = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + b = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(b, Is.Not.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - c = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + c = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(c, Is.Not.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities + 1)); - d = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + d = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(d, Is.Not.Null); } private void Delete(Session session, Key[] createdKeys) { - var a = session.Query.All().Where(e => e.Key==createdKeys[0]).First(); + var a = session.Query.All().Where(e => e.Key == createdKeys[0]).First(); a.Remove(); - var b = session.Query.All().Where(e => e.Key==createdKeys[1]).First(); + var b = session.Query.All().Where(e => e.Key == createdKeys[1]).First(); b.Remove(); - var c = session.Query.All().Where(e => e.Key==createdKeys[2]).First(); + var c = session.Query.All().Where(e => e.Key == createdKeys[2]).First(); c.Remove(); - var d = session.Query.All().Where(e => e.Key==createdKeys[3]).First(); + var d = session.Query.All().Where(e => e.Key == createdKeys[3]).First(); d.Remove(); session.SaveChanges(); - var updatedText = string.Format("{0}_during_upgrade_updated", UpgradeContext.NodeConfiguration.NodeId); + var updatedText = string.Format("{0}_during_upgrade_updated", TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId)); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities)); - a = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + a = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(a, Is.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities)); - b = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + b = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(b, Is.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities)); - c = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + c = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(c, Is.Null); Assert.That(session.Query.All().Count(), Is.EqualTo(initialCountOfEntities)); - d = session.Query.All().Where(e => e.Text==updatedText).FirstOrDefault(); + d = session.Query.All().Where(e => e.Text == updatedText).FirstOrDefault(); Assert.That(d, Is.Null); } + + private string TryGetStorageNodeText(string nodeId) => string.IsNullOrEmpty(nodeId) ? "" : nodeId; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/SimpleTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/SimpleTest.cs index 57daf1014b..4dd8ce0249 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/SimpleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/Requests/SimpleTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017-2020 Xtensive LLC. +// Copyright (C) 2017-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -62,12 +62,16 @@ protected void BuildInitialDomain() foreach (var nodeConfiguration in nodes) { var selectedNode = domain.StorageNodeManager.GetNode(nodeConfiguration.NodeId); using (var session = selectedNode.OpenSession()) - using (session.Activate()) using (var transaction = session.OpenTransaction()) { - _ = new model.Part1.TestEntity1 { Text = session.StorageNodeId }; - _ = new model.Part2.TestEntity2 { Text = session.StorageNodeId }; - _ = new model.Part3.TestEntity3 { Text = session.StorageNodeId }; - _ = new model.Part4.TestEntity4 { Text = session.StorageNodeId }; + + var storageNodeIdText = string.IsNullOrEmpty(session.StorageNodeId) + ? "" + : session.StorageNodeId; + + _ = new model.Part1.TestEntity1(session) { Text = storageNodeIdText }; + _ = new model.Part2.TestEntity2(session) { Text = storageNodeIdText }; + _ = new model.Part3.TestEntity3(session) { Text = storageNodeIdText }; + _ = new model.Part4.TestEntity4(session) { Text = storageNodeIdText }; transaction.Complete(); } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs index 279290aa30..01f54371af 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/Model.cs @@ -23,6 +23,11 @@ public class TestEntity1 : Entity [Field] public string Text { get; set; } + + public TestEntity1(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -33,6 +38,11 @@ public class NewTestEntity1 : Entity [Field] public string Text { get; set; } + + public NewTestEntity1(Session session) + : base(session) + { + } } } @@ -46,6 +56,11 @@ public class TestEntity2 : Entity [Field] public string Text { get; set; } + + public TestEntity2(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -56,6 +71,11 @@ public class NewTestEntity2 : Entity [Field] public string Text { get; set; } + + public NewTestEntity2(Session session) + : base(session) + { + } } } @@ -69,6 +89,11 @@ public class TestEntity3 : Entity [Field] public string Text { get; set; } + + public TestEntity3(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -79,6 +104,11 @@ public class NewTestEntity3 : Entity [Field] public string Text { get; set; } + + public NewTestEntity3(Session session) + : base(session) + { + } } } @@ -92,6 +122,11 @@ public class TestEntity4 : Entity [Field] public string Text { get; set; } + + public TestEntity4(Session session) + : base(session) + { + } } [HierarchyRoot] @@ -102,6 +137,11 @@ public class NewTestEntity4 : Entity [Field] public string Text { get; set; } + + public NewTestEntity4(Session session) + : base(session) + { + } } } @@ -207,6 +247,8 @@ public override void OnStage() private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session session) { + var storageNodeText = TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId); + var typeinfo = session.Domain.Model.Types[typeof(Part1.TestEntity1)]; var testEntity1 = session.StorageNode.Mapping[typeinfo]; var tableRef = SqlDml.TableRef(testEntity1); @@ -214,7 +256,7 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess select.Columns.Add(tableRef["Text"]); var text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); typeinfo = session.Domain.Model.Types[typeof(Part2.TestEntity2)]; var testEntity2 = session.StorageNode.Mapping[typeinfo]; @@ -223,7 +265,7 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess select.Columns.Add(tableRef["Text"]); text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); typeinfo = session.Domain.Model.Types[typeof(Part3.TestEntity3)]; var testEntity3 = session.StorageNode.Mapping[typeinfo]; @@ -232,7 +274,7 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess select.Columns.Add(tableRef["Text"]); text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); typeinfo = session.Domain.Model.Types[typeof(Part4.TestEntity4)]; var testEntity4 = session.StorageNode.Mapping[typeinfo]; @@ -241,7 +283,7 @@ private void ValidateNodeBasedQueriesWork(ISqlExecutor sqlExecutor, Session sess select.Columns.Add(tableRef["Text"]); text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); } private void ValidateSchemaBasedQueriesWork( @@ -253,6 +295,8 @@ private void ValidateSchemaBasedQueriesWork( var databaseMap = GetDatabaseMap(); var schemaMap = GetSchemaMap(); + var storageNodeText = TryGetStorageNodeText(UpgradeContext.NodeConfiguration.NodeId); + var type = typeof(Part1.TestEntity1); var catalogName = catalogNameResolver(databaseMap[type]); var schemaName = schemaNameResolver(schemaMap[type]); @@ -262,7 +306,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); var text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); type = typeof(Part2.TestEntity2); catalogName = catalogNameResolver(databaseMap[type]); @@ -273,7 +317,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); type = typeof(Part3.TestEntity3); catalogName = catalogNameResolver(databaseMap[type]); @@ -284,7 +328,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); type = typeof(Part4.TestEntity4); catalogName = catalogNameResolver(databaseMap[type]); @@ -295,7 +339,7 @@ private void ValidateSchemaBasedQueriesWork( select.Columns.Add(tableRef["Text"]); text = sqlExecutor.ExecuteScalar(select); - Assert.That(text, Is.EqualTo(UpgradeContext.NodeConfiguration.NodeId)); + Assert.That(text, Is.EqualTo(storageNodeText)); } private string ResolveSharedCatalogName(string baseName) => baseName; @@ -325,10 +369,10 @@ private IDictionary GetDatabaseMap() dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.AdditionalDb2); } else { - dictionary.Add(typeof(Part1.TestEntity1), WellKnownDatabases.MultiDatabase.MainDb); - dictionary.Add(typeof(Part2.TestEntity2), WellKnownDatabases.MultiDatabase.MainDb); - dictionary.Add(typeof(Part3.TestEntity3), WellKnownDatabases.MultiDatabase.MainDb); - dictionary.Add(typeof(Part4.TestEntity4), WellKnownDatabases.MultiDatabase.MainDb); + dictionary.Add(typeof(Part1.TestEntity1), UpgradeContext.DefaultSchemaInfo.Database); + dictionary.Add(typeof(Part2.TestEntity2), UpgradeContext.DefaultSchemaInfo.Database); + dictionary.Add(typeof(Part3.TestEntity3), UpgradeContext.DefaultSchemaInfo.Database); + dictionary.Add(typeof(Part4.TestEntity4), UpgradeContext.DefaultSchemaInfo.Database); } return dictionary; } @@ -344,12 +388,14 @@ private IDictionary GetSchemaMap() dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.Schema3); } else { - dictionary.Add(typeof(Part1.TestEntity1), WellKnownSchemas.SqlServerDefaultSchema); - dictionary.Add(typeof(Part2.TestEntity2), WellKnownSchemas.SqlServerDefaultSchema); - dictionary.Add(typeof(Part3.TestEntity3), WellKnownSchemas.SqlServerDefaultSchema); - dictionary.Add(typeof(Part4.TestEntity4), WellKnownSchemas.SqlServerDefaultSchema); + dictionary.Add(typeof(Part1.TestEntity1), UpgradeContext.DefaultSchemaInfo.Schema); + dictionary.Add(typeof(Part2.TestEntity2), UpgradeContext.DefaultSchemaInfo.Schema); + dictionary.Add(typeof(Part3.TestEntity3), UpgradeContext.DefaultSchemaInfo.Schema); + dictionary.Add(typeof(Part4.TestEntity4), UpgradeContext.DefaultSchemaInfo.Schema); } return dictionary; } + + private string TryGetStorageNodeText(string nodeId) => string.IsNullOrEmpty(nodeId) ? "" : nodeId; } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs index 5859d4365f..b79cec09d9 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/MultischemaTest.cs @@ -37,8 +37,8 @@ protected override DomainConfiguration GetDomainConfiguration() protected override List GetNodes(DomainUpgradeMode upgradeMode) { - var @default = new NodeConfiguration(WellKnown.DefaultNodeId) {UpgradeMode = upgradeMode}; - var additional = new NodeConfiguration("Additional") {UpgradeMode = upgradeMode}; + var @default = new NodeConfiguration(WellKnown.DefaultNodeId) { UpgradeMode = upgradeMode }; + var additional = new NodeConfiguration("Additional") { UpgradeMode = upgradeMode }; additional.SchemaMapping.Add(Schema1, Schema2); additional.SchemaMapping.Add(Schema3, Schema4); return new List {@default, additional}; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/SimpleTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/SimpleTest.cs index 9588d16b5c..4a0a36a2af 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/SimpleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/SqlExecutor/SimpleTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2017-2020 Xtensive LLC. +// Copyright (C) 2017-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Kulakov @@ -18,7 +18,7 @@ public class SimpleTest [OneTimeSetUp] public void TestFixtureSetup() => CheckRequirements(); - protected virtual void CheckRequirements() => Require.ProviderIs(StorageProvider.SqlServer); + protected virtual void CheckRequirements() => Require.ProviderIsNot(StorageProvider.Firebird); [Test] public void PerformSafelyTest() @@ -88,16 +88,19 @@ private void BuildInitialDomain() foreach (var nodeConfiguration in nodes) { var selectedNode = domain.StorageNodeManager.GetNode(nodeConfiguration.NodeId); - using (var session = selectedNode.OpenSession()) { - using (session.Activate()) - using (var transaction = session.OpenTransaction()) { - _ = new model.Part1.TestEntity1 { Text = session.StorageNodeId }; - _ = new model.Part2.TestEntity2 { Text = session.StorageNodeId }; - _ = new model.Part3.TestEntity3 { Text = session.StorageNodeId }; - _ = new model.Part4.TestEntity4 { Text = session.StorageNodeId }; - - transaction.Complete(); - } + using (var session = selectedNode.OpenSession()) + using (var transaction = session.OpenTransaction()) { + + var storageNodeIdText = string.IsNullOrEmpty(session.StorageNodeId) + ? "" + : session.StorageNodeId; + + _ = new model.Part1.TestEntity1(session) { Text = storageNodeIdText }; + _ = new model.Part2.TestEntity2(session) { Text = storageNodeIdText }; + _ = new model.Part3.TestEntity3(session) { Text = storageNodeIdText }; + _ = new model.Part4.TestEntity4(session) { Text = storageNodeIdText }; + + transaction.Complete(); } } } From 155980f353ee2cd6e2c377ebcbaa0adc49178a4b Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 4 May 2021 19:42:22 +0500 Subject: [PATCH 55/71] Math Opertions: Cast to result type to get real scale for certain operations --- .../Providers/Expressions/MemberCompilers/MathCompilers.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/MathCompilers.cs b/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/MathCompilers.cs index a54aad76e1..da49f46f37 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/MathCompilers.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/MathCompilers.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 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 @@ -607,7 +607,8 @@ private static SqlExpression TryCastToDecimalPS(SqlExpression value, short preci { var context = ExpressionTranslationContext.Current; var provider = context.ProviderInfo.ProviderName; - if (provider.Equals(WellKnown.Provider.PostgreSql, StringComparison.Ordinal)) { + if (provider.Equals(WellKnown.Provider.PostgreSql, StringComparison.Ordinal) + || provider.Equals(WellKnown.Provider.Oracle, StringComparison.Ordinal)) { // to fit result into .Net decimal since Npgsql client libarary does not provide a way to make in on reading return SqlDml.Cast(value, SqlType.Decimal, precision, scale); } From ac97538f2d5cf20f678a59d29e90a1c3df2a072c Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 4 May 2021 20:20:51 +0500 Subject: [PATCH 56/71] Move IgnoreRulesTest to Storage namespace --- .../SchemaSharing/IgnoreRulesTest.cs | 4 +- .../Storage/SchemaSharing/Model.cs | 81 +++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) rename Orm/Xtensive.Orm.Tests/{Upgrade => Storage}/SchemaSharing/IgnoreRulesTest.cs (99%) create mode 100644 Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/Model.cs diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/IgnoreRulesTest.cs similarity index 99% rename from Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs rename to Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/IgnoreRulesTest.cs index 9c887ab09e..85a9eb9435 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SchemaSharing/IgnoreRulesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/IgnoreRulesTest.cs @@ -12,9 +12,9 @@ using Xtensive.Orm.Providers; using Xtensive.Sql; using Xtensive.Sql.Model; -using Xtensive.Orm.Tests.Upgrade.SchemaSharing.Model; +using Xtensive.Orm.Tests.Storage.SchemaSharing.Model; -namespace Xtensive.Orm.Tests.Upgrade.SchemaSharing +namespace Xtensive.Orm.Tests.Storage.SchemaSharing { [TestFixture] public class IgnoreRulesTest : AutoBuildTest diff --git a/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/Model.cs b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/Model.cs new file mode 100644 index 0000000000..79bca128f1 --- /dev/null +++ b/Orm/Xtensive.Orm.Tests/Storage/SchemaSharing/Model.cs @@ -0,0 +1,81 @@ +// Copyright (C) 2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; + +namespace Xtensive.Orm.Tests.Storage.SchemaSharing.Model +{ + [HierarchyRoot] + public class Product : Entity + { + [Field, Key] + public int Id { get; set; } + + [Field] + public string Name { get; set; } + } + + [HierarchyRoot] + public class PriceList : Entity + { + [Field, Key] + public int Id { get; set; } + + [Field] + public DateTime CreatedOn { get; set; } + + [Field] + public bool IsArchived { get; set; } + + [Field] + public EntitySet Items { get; set; } + } + + [HierarchyRoot] + public class PriceListItem : Entity + { + [Field, Key] + public int Id { get; set; } + + [Field] + [Association(PairTo = "Items", OnOwnerRemove = OnRemoveAction.Clear, OnTargetRemove = OnRemoveAction.Cascade)] + public PriceList PriceList { get; set; } + + [Field] + [Association(OnOwnerRemove = OnRemoveAction.None, OnTargetRemove = OnRemoveAction.Deny)] + public Product Product { get; set; } + + [Field] + public double Price { get; set; } + + [Field] + public Currency Currency { get; set; } + } + + [HierarchyRoot] + public class Currency : Entity + { + [Field, Key] + public int Id { get; set; } + + [Field] + public string Name { get; set; } + + [Field] + public string ShortName { get; set; } + + [Field] + public string Symbol { get; set; } + } + + [HierarchyRoot] + public class TypeForUgrade : Entity + { + [Field, Key] + public int Id { get; set; } + + [Field] + public string Text { get; set; } + } +} From 9dfb09df12cb46d262e097fc3fd698050cfeb769 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 4 May 2021 21:29:32 +0500 Subject: [PATCH 57/71] Apply workaround for Oracle lack of native Int support --- .../Storage/IgnoreRulesValidateTest.cs | 80 ++++++++++++------- 1 file changed, 51 insertions(+), 29 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs index 3d95578fc1..111ea8460f 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs @@ -309,7 +309,7 @@ public void IgnoreSimpleColumnTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.Int32)); + CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", GetTypeForInteger(SqlType.Int32)); var ignoreRuleCollection = new IgnoreRuleCollection(); _ = ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); @@ -325,7 +325,7 @@ public void IgnoreReferencedColumnTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); CreateForeignKeyInDb(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity1_MyEntity1ID"); var ignoreRuleCollection = new IgnoreRuleCollection(); _ = ignoreRuleCollection.IgnoreColumn("ReferencedIgnoredColumn").WhenTable("MyEntity2").WhenSchema(schema); @@ -341,7 +341,7 @@ public void IgnoreSimpleTableTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; var addedColumnsNames = new[] { "Id", "FirstColumn" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64) }; if (createConstraintsWithTable) { var delayedOp = CreateTableDelayed(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); @@ -366,7 +366,7 @@ public void IgnoreReferencedTableTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; if (createConstraintsWithTable) { var delayedOp = CreateTableDelayed(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); @@ -393,7 +393,7 @@ public void InsertIntoTableWithIgnoredColumnTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "Myentity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema, "Myentity2", "SimpleIgnoredColumn", GetTypeForInteger(SqlType.Int64)); var ignoreRuleCollection = new IgnoreRuleCollection(); _ = ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); @@ -416,7 +416,7 @@ public void InsertIntoTableWithNotNullableIgnoredColumnTest() var catalog = GetCatalog(); var schema = catalog.Schemas[catalog.DefaultSchema.Name] ?? catalog.Schemas[0]; - schema.Tables["MyEntity2"].CreateColumn("SimpleIgnoredColumn", new SqlValueType(SqlType.Int64)).IsNullable = false; + schema.Tables["MyEntity2"].CreateColumn("SimpleIgnoredColumn", GetTypeForInteger(SqlType.Int64)).IsNullable = false; var alter = SqlDdl.Alter(schema.Tables["MyEntity2"], SqlDdl.AddColumn(schema.Tables["MyEntity2"].TableColumns["SimpleIgnoredColumn"])); @@ -443,7 +443,7 @@ public void DropTableWithIgnoredColumnTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "SimpleIgnoredColumn", GetTypeForInteger(SqlType.Int64)); var ignoreRuleCollection = new IgnoreRuleCollection(); _ = ignoreRuleCollection.IgnoreColumn("SimpleIgnoredColumn").WhenTable("MyEntity2"); @@ -462,7 +462,7 @@ public void DropReferencedTableTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); CreateForeignKeyInDb(catalog, schema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity1_MyEntity1ID"); var ignoreRuleCollection = new IgnoreRuleCollection(); @@ -480,9 +480,9 @@ public void IgnoreColumnsByMaskValidateTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; - CreateColumn(catalog, schema, "MyEntity2", "IgnoreFirstColumn", new SqlValueType(SqlType.Int64)); - CreateColumn(catalog, schema, "MyEntity2", "IgnoreSecondColumn", new SqlValueType(SqlType.Int64)); - CreateColumn(catalog, schema, "MyEntity2", "IgnoreThirdColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "IgnoreFirstColumn", GetTypeForInteger(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "IgnoreSecondColumn", GetTypeForInteger(SqlType.Int64)); + CreateColumn(catalog, schema, "MyEntity2", "IgnoreThirdColumn", GetTypeForInteger(SqlType.Int64)); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("Ignore*"); @@ -497,7 +497,7 @@ public void IgnoreTablesByMaskValidateTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; var addedColumnsNames = new[] { "Id", "FirstColumn", "SecondColumn" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; if (createConstraintsWithTable) { var delayedOp = CreateTableDelayed(catalog, schema, "IgnoredFirstTable", addedColumnsNames, addedColumnsTypes); @@ -529,7 +529,7 @@ public void IgnoreAllColumnsInTableByMaskValidateTest() var catalog = GetCatalog(); var schema = catalog.DefaultSchema.Name; var addedColumnsNames = new[] { "Id", "FirstColumn", "SecondColumn" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; if (createConstraintsWithTable) { var delayedOp = CreateTableDelayed(catalog, schema, "IgnoredTable", addedColumnsNames, addedColumnsTypes); @@ -554,8 +554,8 @@ public void UpgradeDomainWithIgnoreRuleByMaskInPerformModeTest() var catalog = GetCatalog(); var schema = catalog.Schemas[catalog.DefaultSchema.Name] ?? catalog.Schemas[0]; - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", new SqlValueType(SqlType.Int64)); - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", GetTypeForInteger(SqlType.Int64)); + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", GetTypeForInteger(SqlType.Int64)); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("Ignored*").WhenTable("MyEntity2"); @@ -583,8 +583,8 @@ public void UpgradeDomainWithIgnoreRuleByMaskInPerformSafelyModeTest() var catalog = GetCatalog(); var schema = catalog.Schemas[catalog.DefaultSchema.Name] ?? catalog.Schemas[0]; - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", new SqlValueType(SqlType.Int64)); - CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredFirstColumn", GetTypeForInteger(SqlType.Int64)); + CreateColumn(catalog, schema.Name, "MyEntity2", "IgnoredSecondColumn", GetTypeForInteger(SqlType.Int64)); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("Ignored*"); @@ -619,11 +619,11 @@ public void MultischemaValidateTest() BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); catalog = GetCatalog(); - CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); @@ -648,11 +648,11 @@ public void MultidatabaseValidateTest() BuildComplexDomain(DomainUpgradeMode.Recreate, null, new[] { typeof(Model1.Customer) }, new[] { typeof(Model3.MyEntity1) }).Dispose(); var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); - CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); + CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64), true); CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(secondCatalog, defaultSchema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); CreatePrimaryKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); @@ -680,11 +680,11 @@ public void MultischemaUpgrageInPerformModeTest() BuildDomainAndFillData(); catalog = GetCatalog(); - CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); @@ -717,11 +717,11 @@ public void MultischemaUpgrageInPerformSafelyModeTest() BuildDomainAndFillData(); catalog = GetCatalog(); - CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64)); + CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); @@ -751,11 +751,11 @@ public void MultidatabaseUpgradeInPerformModeTest() BuildDomainAndFillData(); var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); - CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); + CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64), true); CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(secondCatalog, defaultSchema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); CreatePrimaryKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); @@ -784,10 +784,10 @@ public void MultidatabaseUpgradeInPerformSafelyModeTest() BuildDomainAndFillData(); var secondCatalog = GetCatalog(Multimapping.MultidatabaseTest.Database2Name); - CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", new SqlValueType(SqlType.Int64), true); + CreateColumn(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64), true); CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID", true); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; - var addedColumnsTypes = new[] { new SqlValueType(SqlType.Int32), new SqlValueType(SqlType.Int64), new SqlValueType(SqlType.Int64) }; + var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(secondCatalog, defaultSchema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes, true); CreatePrimaryKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id", true); CreateForeignKeyInDb(secondCatalog, defaultSchema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id", true); @@ -1130,5 +1130,27 @@ private void ClearMultidatabaseAndMultischemaFlags() isMultidatabaseTest = false; isMultischemaTest = false; } + + private SqlValueType GetTypeForInteger(SqlType sqlType) + { + if (!StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Oracle)) { + return new SqlValueType(sqlType); + } + + const int ShortPrecision = 5; + const int IntPrecision = 10; + const int LongPrecision = 20; + + if (sqlType == SqlType.Int16) { + return new SqlValueType(SqlType.Decimal, ShortPrecision, 0); + } + if (sqlType == SqlType.Int32) { + return new SqlValueType(SqlType.Decimal, IntPrecision, 0); + } + if (sqlType == SqlType.Int64) { + return new SqlValueType(SqlType.Decimal, LongPrecision, 0); + } + return new SqlValueType(sqlType); + } } } From bd0dbfabecd0e57a1bf275df90d7645bc08d2bb7 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 4 May 2021 21:29:59 +0500 Subject: [PATCH 58/71] No multiple domain building --- .../Storage/SkippingValidationOnCommitTest.cs | 2850 ++++++++--------- 1 file changed, 1342 insertions(+), 1508 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs index b20dad5e16..b2d56e022d 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (C) 2017-2021 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.Diagnostics; using System.Linq; @@ -8,63 +12,72 @@ using Xtensive.Orm.Tests.Linq; using Xtensive.Orm.Tests.Model.Association; using Xtensive.Orm.Validation; -using model1 = Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel.NoConstraintsModel; -using model2 = Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel.ImmediateConstrainstModel; -using model3 = Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel.ImmediateAndSkippedContstraintsModel; -using model4 = Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel.NonImmediateConstraintsModel; -using model5 = Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel.NonImmediateAndSkippedConstrainstsModel; +using Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel; namespace Xtensive.Orm.Tests.Storage { [TestFixture] - public class SkippingValidationOnCommitTest + public class SkippingValidationOnCommitTest : AutoBuildTest { - [SetUp] - public void BeforeEachTestSetup() - { - try { - using (var domain = Domain.Build(GetInitialDomainConfiguration())) { - PopulateData(domain); - } - } - catch (IgnoreException) { - throw; - } - catch (Exception e) { - Debug.WriteLine(e); - throw; - } - } - - private DomainConfiguration GetInitialDomainConfiguration() + protected override DomainConfiguration BuildConfiguration() { - var configuration = DomainConfigurationFactory.Create(); + var configuration = base.BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (model1.BaseEntity).Assembly, typeof (model1.BaseEntity).Namespace); + configuration.Types.Register(typeof(BaseEntity).Assembly, typeof(BaseEntity).Namespace); return configuration; } - private DomainConfiguration GetDomainConfiguration(Type typeOfTargetNamespace) + protected override void PopulateData() { - var configuration = DomainConfigurationFactory.Create(); - configuration.UpgradeMode = DomainUpgradeMode.PerformSafely; - configuration.Types.Register(typeOfTargetNamespace.Assembly, typeOfTargetNamespace.Namespace); - return configuration; - } + var sessionConfiguration = new SessionConfiguration(SessionOptions.AutoSaveChanges); + using (var session = Domain.OpenSession(sessionConfiguration)) + using (session.Activate()) + using (var transaction = session.OpenTransaction()) { - private void PopulateData(Domain domain) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model1.EmailTestEntity() {NeverValidatedField = "Email", EmailField = "not email"}; - new model1.FutureTestEntity() {NeverValidatedField = "Future", DateField = DateTime.Now.AddMonths(-1)}; - new model1.LenghtTestEntity() {NeverValidatedField = "Length", StringField = "too short"}; - new model1.NotEmptyTestEntity() {NeverValidatedField = "NotEmpty", StringField = string.Empty}; - new model1.NotNullOrEmptyTestEntity() {NeverValidatedField = "NotNullOrEmpty", StringField = null}; - new model1.NotNullTestEntity() {NeverValidatedField = "NotNull", StringField = null}; - new model1.PastTestEntity() {NeverValidatedField = "Past", DateField = DateTime.Now.AddMonths(1)}; - new model1.RangeTestEntity() {NeverValidatedField = "Range", LongField = -100}; - new model1.RegexTestEntity() {NeverValidatedField = "Regex", StringField = "abcd"}; + _ = new EmailTestEntity1() { NeverValidatedField = "Email", EmailField = "not email" }; + _ = new EmailTestEntity2() { NeverValidatedField = "Email", EmailField = "not email" }; + _ = new EmailTestEntity3() { NeverValidatedField = "Email", EmailField = "not email" }; + _ = new EmailTestEntity4() { NeverValidatedField = "Email", EmailField = "not email" }; + + _ = new FutureTestEntity1() { NeverValidatedField = "Future", DateField = DateTime.Now.AddMonths(-1) }; + _ = new FutureTestEntity2() { NeverValidatedField = "Future", DateField = DateTime.Now.AddMonths(-1) }; + _ = new FutureTestEntity3() { NeverValidatedField = "Future", DateField = DateTime.Now.AddMonths(-1) }; + _ = new FutureTestEntity4() { NeverValidatedField = "Future", DateField = DateTime.Now.AddMonths(-1) }; + + _ = new LenghtTestEntity1() { NeverValidatedField = "Length", StringField = "too short" }; + _ = new LenghtTestEntity2() { NeverValidatedField = "Length", StringField = "too short" }; + _ = new LenghtTestEntity3() { NeverValidatedField = "Length", StringField = "too short" }; + _ = new LenghtTestEntity4() { NeverValidatedField = "Length", StringField = "too short" }; + + _ = new NotEmptyTestEntity1() { NeverValidatedField = "NotEmpty", StringField = string.Empty }; + _ = new NotEmptyTestEntity2() { NeverValidatedField = "NotEmpty", StringField = string.Empty }; + _ = new NotEmptyTestEntity3() { NeverValidatedField = "NotEmpty", StringField = string.Empty }; + _ = new NotEmptyTestEntity4() { NeverValidatedField = "NotEmpty", StringField = string.Empty }; + + _ = new NotNullOrEmptyTestEntity1() { NeverValidatedField = "NotNullOrEmpty", StringField = null }; + _ = new NotNullOrEmptyTestEntity2() { NeverValidatedField = "NotNullOrEmpty", StringField = null }; + _ = new NotNullOrEmptyTestEntity3() { NeverValidatedField = "NotNullOrEmpty", StringField = null }; + _ = new NotNullOrEmptyTestEntity4() { NeverValidatedField = "NotNullOrEmpty", StringField = null }; + + _ = new NotNullTestEntity1() { NeverValidatedField = "NotNull", StringField = null }; + _ = new NotNullTestEntity2() { NeverValidatedField = "NotNull", StringField = null }; + _ = new NotNullTestEntity3() { NeverValidatedField = "NotNull", StringField = null }; + _ = new NotNullTestEntity4() { NeverValidatedField = "NotNull", StringField = null }; + + _ = new PastTestEntity1() { NeverValidatedField = "Past", DateField = DateTime.Now.AddMonths(1) }; + _ = new PastTestEntity2() { NeverValidatedField = "Past", DateField = DateTime.Now.AddMonths(1) }; + _ = new PastTestEntity3() { NeverValidatedField = "Past", DateField = DateTime.Now.AddMonths(1) }; + _ = new PastTestEntity4() { NeverValidatedField = "Past", DateField = DateTime.Now.AddMonths(1) }; + + _ = new RangeTestEntity1() { NeverValidatedField = "Range", LongField = -100 }; + _ = new RangeTestEntity2() { NeverValidatedField = "Range", LongField = -100 }; + _ = new RangeTestEntity3() { NeverValidatedField = "Range", LongField = -100 }; + _ = new RangeTestEntity4() { NeverValidatedField = "Range", LongField = -100 }; + + _ = new RegexTestEntity1() { NeverValidatedField = "Regex", StringField = "abcd" }; + _ = new RegexTestEntity2() { NeverValidatedField = "Regex", StringField = "abcd" }; + _ = new RegexTestEntity3() { NeverValidatedField = "Regex", StringField = "abcd" }; + _ = new RegexTestEntity4() { NeverValidatedField = "Regex", StringField = "abcd" }; transaction.Complete(); } @@ -73,37 +86,35 @@ private void PopulateData(Domain domain) [Test] public void EmailConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model2.EmailTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -111,73 +122,69 @@ public void EmailConstraintImmediateNotSkippedTest() [Test] public void EmailConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.EmailTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void EmailConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model4.EmailTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -185,81 +192,76 @@ public void EmailConstraintNotImmidiateNotSkippedTest() [Test] public void EmailConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.EmailTestEntity)))) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.EmailTestEntity() {NeverValidatedField = "", EmailField = "not email"};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new EmailTestEntity4() { NeverValidatedField = "", EmailField = "not email" };//no exception + transaction.Complete(); + // no exception } } [Test] public void FutureConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model2.FutureTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -267,73 +269,69 @@ public void FutureConstraintImmediateNotSkippedTest() [Test] public void FutureConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.FutureTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void FutureConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model4.FutureTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -341,81 +339,76 @@ public void FutureConstraintNotImmidiateNotSkippedTest() [Test] public void FutureConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.FutureTestEntity)))) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.FutureTestEntity() {NeverValidatedField = "", DateField = DateTime.Now.AddMonths(-1)};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new FutureTestEntity4() { NeverValidatedField = "", DateField = DateTime.Now.AddMonths(-1) };//no exception + transaction.Complete(); + // no exception } } [Test] public void LenghtConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model2.EmailTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -423,73 +416,69 @@ public void LenghtConstraintImmediateNotSkippedTest() [Test] public void LenghtConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.LenghtTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void LenghtConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model4.LenghtTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -497,80 +486,76 @@ public void LenghtConstraintNotImmidiateNotSkippedTest() [Test] public void LenghtConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.LenghtTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.LenghtTestEntity() {NeverValidatedField = "", StringField = "not email"};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new LenghtTestEntity4() { NeverValidatedField = "", StringField = "not email" };//no exception + transaction.Complete(); + // no exception } } [Test] public void NotEmptyConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model2.NotEmptyTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -578,73 +563,69 @@ public void NotEmptyConstraintImmediateNotSkippedTest() [Test] public void NotEmptyConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.NotEmptyTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void NotEmptyConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model4.NotEmptyTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -652,81 +633,76 @@ public void NotEmptyConstraintNotImmidiateNotSkippedTest() [Test] public void NotEmptyConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.NotEmptyTestEntity)))) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.NotEmptyTestEntity() {NeverValidatedField = "NotEmpty", StringField = ""};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new NotEmptyTestEntity4() { NeverValidatedField = "NotEmpty", StringField = "" };//no exception + transaction.Complete(); + // no exception } } [Test] public void NotNullConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model2.NotNullTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -734,73 +710,69 @@ public void NotNullConstraintImmediateNotSkippedTest() [Test] public void NotNullConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.NotNullTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void NotNullConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model4.NotNullTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -808,156 +780,146 @@ public void NotNullConstraintNotImmidiateNotSkippedTest() [Test] public void NotNullConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.NotNullTestEntity)))) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.NotNullTestEntity() {NeverValidatedField = "NotNull", StringField = null};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new NotNullTestEntity4() { NeverValidatedField = "NotNull", StringField = null };//no exception + transaction.Complete(); + // no exception } } [Test] public void NotNullOrEmptyConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model2.NotNullOrEmptyTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); - } [Test] public void NotNullOrEmptyConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.NotNullOrEmptyTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void NotNullOrEmptyConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model4.NotNullOrEmptyTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -965,81 +927,76 @@ public void NotNullOrEmptyConstraintNotImmidiateNotSkippedTest() [Test] public void NotNullOrEmptyConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.NotNullOrEmptyTestEntity)))) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.NotNullOrEmptyTestEntity() {NeverValidatedField = "NotNullOrEmpty", StringField = null};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new NotNullOrEmptyTestEntity4() { NeverValidatedField = "NotNullOrEmpty", StringField = null };//no exception + transaction.Complete(); + // no exception } } [Test] public void PastConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model2.PastTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -1047,73 +1004,69 @@ public void PastConstraintImmediateNotSkippedTest() [Test] public void PastConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.EmailTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void PastConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model4.PastTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -1121,80 +1074,76 @@ public void PastConstraintNotImmidiateNotSkippedTest() [Test] public void PastConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model5.PastTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.PastTestEntity() { NeverValidatedField = "Past", DateField = DateTime.Now.AddMonths(2) };//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new PastTestEntity4() { NeverValidatedField = "Past", DateField = DateTime.Now.AddMonths(2) };//no exception + transaction.Complete(); + // no exception } } [Test] public void RangeConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model2.RangeTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -1202,73 +1151,69 @@ public void RangeConstraintImmediateNotSkippedTest() [Test] public void RangeConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.RangeTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void RangeConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model4.RangeTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -1276,81 +1221,75 @@ public void RangeConstraintNotImmidiateNotSkippedTest() [Test] public void RangeConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.RangeTestEntity)))) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.RangeTestEntity() {NeverValidatedField = "Range", LongField = -200};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new RangeTestEntity4() { NeverValidatedField = "Range", LongField = -200 };//no exception + transaction.Complete(); + // no exception } } [Test] public void RegexConstraintImmediateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model2.RegexTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -1358,73 +1297,69 @@ public void RegexConstraintImmediateNotSkippedTest() [Test] public void RegexConstraintImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model3.RegexTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit } } [Test] public void RegexConstraintNotImmidiateNotSkippedTest() { - Assert.Throws(() => { - using (var domain = Domain.Build(GetDomainConfiguration(typeof (model4.RegexTestEntity)))) { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } + + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } + + _ = Assert.Throws(() => { + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //exception on commit } }); } @@ -1432,44 +1367,41 @@ public void RegexConstraintNotImmidiateNotSkippedTest() [Test] public void RegexConstraintNotImmediateSkippedTest() { - using (var domain = Domain.Build(GetDomainConfiguration(typeof(model5.RegexTestEntity)))) - { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => entity.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => entity.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - Assert.Throws(() => session.Validate()); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + _ = Assert.Throws(() => session.Validate()); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); - entity.NeverValidatedField = entity.NeverValidatedField + "(changed)"; - transaction.Complete(); - //no exception on commit - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().First(); + entity.NeverValidatedField += "(changed)"; + transaction.Complete(); + //no exception on commit + } - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - new model5.RegexTestEntity() {NeverValidatedField = "Regex", StringField = "bbbbbb"};//no exception - transaction.Complete(); - // no exception - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + _ = new RegexTestEntity4() { NeverValidatedField = "Regex", StringField = "bbbbbb" };//no exception + transaction.Complete(); + // no exception } } } @@ -1477,414 +1409,316 @@ public void RegexConstraintNotImmediateSkippedTest() namespace Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel { - namespace NoConstraintsModel + public abstract class BaseEntity : Entity { - public abstract class BaseEntity : Entity - { - [Field, Key] - public long Id { get; private set; } - - [Field] - public string NeverValidatedField { get; set; } - } - - [HierarchyRoot] - public class EmailTestEntity : BaseEntity - { - [Field] - public string EmailField { get; set; } - } + [Field, Key] + public long Id { get; private set; } - [HierarchyRoot] - public class FutureTestEntity : BaseEntity - { - [Field] - public DateTime DateField { get; set; } - } - - [HierarchyRoot] - public class LenghtTestEntity : BaseEntity - { - [Field] - public string StringField { get; set; } - } - - [HierarchyRoot] - public class NotEmptyTestEntity : BaseEntity - { - [Field] - public string StringField { get; set; } - } - - [HierarchyRoot] - public class NotNullTestEntity : BaseEntity - { - [Field] - public string StringField { get; set; } - } - - [HierarchyRoot] - public class NotNullOrEmptyTestEntity : BaseEntity - { - [Field] - public string StringField { get; set; } - } - - [HierarchyRoot] - public class PastTestEntity : BaseEntity - { - [Field] - public DateTime DateField { get; set; } - } + [Field] + public string NeverValidatedField { get; set; } + } - [HierarchyRoot] - public class RangeTestEntity : BaseEntity - { - [Field] - public long LongField { get; set; } - } + #region ImmediateConstraints - [HierarchyRoot] - public class RegexTestEntity : BaseEntity - { - [Field] - public string StringField { get; set; } - } + [HierarchyRoot] + public class EmailTestEntity1 : BaseEntity + { + [Field] + [EmailConstraint(IsImmediate = true)] + public string EmailField { get; set; } } - namespace ImmediateConstrainstModel + [HierarchyRoot] + public class FutureTestEntity1 : BaseEntity { - public abstract class BaseEntity : Entity - { - [Field, Key] - public long Id { get; private set; } + [Field] + [FutureConstraint(IsImmediate = true)] + public DateTime DateField { get; set; } + } - [Field] - public string NeverValidatedField { get; set; } - } + [HierarchyRoot] + public class LenghtTestEntity1 : BaseEntity + { + [Field] + [LengthConstraint(IsImmediate = true, Min = 16)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class EmailTestEntity : BaseEntity - { - [Field] - [EmailConstraint(IsImmediate = true)] - public string EmailField { get; set; } - } + [HierarchyRoot] + public class NotEmptyTestEntity1 : BaseEntity + { + [Field] + [NotEmptyConstraint(IsImmediate = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class FutureTestEntity : BaseEntity - { - [Field] - [FutureConstraint(IsImmediate = true)] - public DateTime DateField { get; set; } - } + [HierarchyRoot] + public class NotNullTestEntity1 : BaseEntity + { + [Field] + [NotNullConstraint(IsImmediate = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class LenghtTestEntity : BaseEntity - { - [Field] - [LengthConstraint(IsImmediate = true, Min = 16)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class NotNullOrEmptyTestEntity1 : BaseEntity + { + [Field] + [NotNullOrEmptyConstraint(IsImmediate = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class NotEmptyTestEntity : BaseEntity - { - [Field] - [NotEmptyConstraint(IsImmediate = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class PastTestEntity1 : BaseEntity + { + [Field] + [PastConstraint(IsImmediate = true)] + public DateTime DateField { get; set; } + } - [HierarchyRoot] - public class NotNullTestEntity : BaseEntity - { - [Field] - [NotNullConstraint(IsImmediate = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class RangeTestEntity1 : BaseEntity + { + [Field] + [RangeConstraint(IsImmediate = true, Min = 10, Max = 20)] + public long LongField { get; set; } + } - [HierarchyRoot] - public class NotNullOrEmptyTestEntity : BaseEntity - { - [Field] - [NotNullOrEmptyConstraint(IsImmediate = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class RegexTestEntity1 : BaseEntity + { + [Field] + [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class PastTestEntity : BaseEntity - { - [Field] - [PastConstraint(IsImmediate = true)] - public DateTime DateField { get; set; } - } + #endregion - [HierarchyRoot] - public class RangeTestEntity : BaseEntity - { - [Field] - [RangeConstraint(IsImmediate = true, Min = 10, Max = 20)] - public long LongField { get; set; } - } + #region ImmediateAndSkippedContstraints - [HierarchyRoot] - public class RegexTestEntity : BaseEntity - { - [Field] - [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class EmailTestEntity2 : BaseEntity + { + [Field] + [EmailConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] + public string EmailField { get; set; } } - namespace ImmediateAndSkippedContstraintsModel + [HierarchyRoot] + public class FutureTestEntity2 : BaseEntity { - public abstract class BaseEntity : Entity - { - [Field, Key] - public long Id { get; private set; } + [Field] + [FutureConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] + public DateTime DateField { get; set; } + } - [Field] - public string NeverValidatedField { get; set; } - } + [HierarchyRoot] + public class LenghtTestEntity2 : BaseEntity + { + [Field] + [LengthConstraint(IsImmediate = true, SkipOnTransactionCommit = true, Min = 16)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class EmailTestEntity : BaseEntity - { - [Field] - [EmailConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] - public string EmailField { get; set; } - } + [HierarchyRoot] + public class NotEmptyTestEntity2 : BaseEntity + { + [Field] + [NotEmptyConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class FutureTestEntity : BaseEntity - { - [Field] - [FutureConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] - public DateTime DateField { get; set; } - } + [HierarchyRoot] + public class NotNullTestEntity2 : BaseEntity + { + [Field] + [NotNullConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class LenghtTestEntity : BaseEntity - { - [Field] - [LengthConstraint(IsImmediate = true, SkipOnTransactionCommit = true, Min = 16)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class NotNullOrEmptyTestEntity2 : BaseEntity + { + [Field] + [NotNullOrEmptyConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class NotEmptyTestEntity : BaseEntity - { - [Field] - [NotEmptyConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class PastTestEntity2 : BaseEntity + { + [Field] + [PastConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] + public DateTime DateField { get; set; } + } - [HierarchyRoot] - public class NotNullTestEntity : BaseEntity - { - [Field] - [NotNullConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class RangeTestEntity2 : BaseEntity + { + [Field] + [RangeConstraint(IsImmediate = true, SkipOnTransactionCommit = true, Min = 10, Max = 20)] + public long LongField { get; set; } + } - [HierarchyRoot] - public class NotNullOrEmptyTestEntity : BaseEntity - { - [Field] - [NotNullOrEmptyConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class RegexTestEntity2 : BaseEntity + { + [Field] + [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = true, SkipOnTransactionCommit = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class PastTestEntity : BaseEntity - { - [Field] - [PastConstraint(IsImmediate = true, SkipOnTransactionCommit = true)] - public DateTime DateField { get; set; } - } + #endregion - [HierarchyRoot] - public class RangeTestEntity : BaseEntity - { - [Field] - [RangeConstraint(IsImmediate = true, SkipOnTransactionCommit = true, Min = 10, Max = 20)] - public long LongField { get; set; } - } + #region NonImmediateConstraints - [HierarchyRoot] - public class RegexTestEntity : BaseEntity - { - [Field] - [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = true, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class EmailTestEntity3 : BaseEntity + { + [Field] + [EmailConstraint(IsImmediate = false)] + public string EmailField { get; set; } } - namespace NonImmediateConstraintsModel + [HierarchyRoot] + public class FutureTestEntity3 : BaseEntity { - public abstract class BaseEntity : Entity - { - [Field, Key] - public long Id { get; private set; } + [Field] + [FutureConstraint(IsImmediate = false)] + public DateTime DateField { get; set; } + } - [Field] - public string NeverValidatedField { get; set; } - } + [HierarchyRoot] + public class LenghtTestEntity3 : BaseEntity + { + [Field] + [LengthConstraint(IsImmediate = false, Min = 16)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class EmailTestEntity : BaseEntity - { - [Field] - [EmailConstraint(IsImmediate = false)] - public string EmailField { get; set; } - } + [HierarchyRoot] + public class NotEmptyTestEntity3 : BaseEntity + { + [Field] + [NotEmptyConstraint(IsImmediate = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class FutureTestEntity : BaseEntity - { - [Field] - [FutureConstraint(IsImmediate = false)] - public DateTime DateField { get; set; } - } + [HierarchyRoot] + public class NotNullTestEntity3 : BaseEntity + { + [Field] + [NotNullConstraint(IsImmediate = false)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class LenghtTestEntity : BaseEntity - { - [Field] - [LengthConstraint(IsImmediate = false, Min = 16)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class NotNullOrEmptyTestEntity3 : BaseEntity + { + [Field] + [NotNullOrEmptyConstraint(IsImmediate = false)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class NotEmptyTestEntity : BaseEntity - { - [Field] - [NotEmptyConstraint(IsImmediate = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class PastTestEntity3 : BaseEntity + { + [Field] + [PastConstraint(IsImmediate = false)] + public DateTime DateField { get; set; } + } - [HierarchyRoot] - public class NotNullTestEntity : BaseEntity - { - [Field] - [NotNullConstraint(IsImmediate = false)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class RangeTestEntity3 : BaseEntity + { + [Field] + [RangeConstraint(IsImmediate = false, Min = 10, Max = 20)] + public long LongField { get; set; } + } - [HierarchyRoot] - public class NotNullOrEmptyTestEntity : BaseEntity - { - [Field] - [NotNullOrEmptyConstraint(IsImmediate = false)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class RegexTestEntity3 : BaseEntity + { + [Field] + [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = false)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class PastTestEntity : BaseEntity - { - [Field] - [PastConstraint(IsImmediate = false)] - public DateTime DateField { get; set; } - } + #endregion - [HierarchyRoot] - public class RangeTestEntity : BaseEntity - { - [Field] - [RangeConstraint(IsImmediate = false, Min = 10, Max = 20)] - public long LongField { get; set; } - } + #region NonImmediateAndSkippedConstrainsts - [HierarchyRoot] - public class RegexTestEntity : BaseEntity - { - [Field] - [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = false)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class EmailTestEntity4 : BaseEntity + { + [Field] + [EmailConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] + public string EmailField { get; set; } } - namespace NonImmediateAndSkippedConstrainstsModel + [HierarchyRoot] + public class FutureTestEntity4 : BaseEntity { - public abstract class BaseEntity : Entity - { - [Field, Key] - public long Id { get; private set; } - - [Field] - public string NeverValidatedField { get; set; } - } - - [HierarchyRoot] - public class EmailTestEntity : BaseEntity - { - [Field] - [EmailConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] - public string EmailField { get; set; } - } - - [HierarchyRoot] - public class FutureTestEntity : BaseEntity - { - [Field] - [FutureConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] - public DateTime DateField { get; set; } - } + [Field] + [FutureConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] + public DateTime DateField { get; set; } + } - [HierarchyRoot] - public class LenghtTestEntity : BaseEntity - { - [Field] - [LengthConstraint(IsImmediate = false, SkipOnTransactionCommit = true, Min = 16)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class LenghtTestEntity4 : BaseEntity + { + [Field] + [LengthConstraint(IsImmediate = false, SkipOnTransactionCommit = true, Min = 16)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class NotEmptyTestEntity : BaseEntity - { - [Field] - [NotEmptyConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class NotEmptyTestEntity4 : BaseEntity + { + [Field] + [NotEmptyConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class NotNullTestEntity : BaseEntity - { - [Field] - [NotNullConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class NotNullTestEntity4 : BaseEntity + { + [Field] + [NotNullConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class NotNullOrEmptyTestEntity : BaseEntity - { - [Field] - [NotNullOrEmptyConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class NotNullOrEmptyTestEntity4 : BaseEntity + { + [Field] + [NotNullOrEmptyConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] + public string StringField { get; set; } + } - [HierarchyRoot] - public class PastTestEntity : BaseEntity - { - [Field] - [PastConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] - public DateTime DateField { get; set; } - } + [HierarchyRoot] + public class PastTestEntity4 : BaseEntity + { + [Field] + [PastConstraint(IsImmediate = false, SkipOnTransactionCommit = true)] + public DateTime DateField { get; set; } + } - [HierarchyRoot] - public class RangeTestEntity : BaseEntity - { - [Field] - [RangeConstraint(IsImmediate = false, SkipOnTransactionCommit = true, Min = 10, Max = 20)] - public long LongField { get; set; } - } + [HierarchyRoot] + public class RangeTestEntity4 : BaseEntity + { + [Field] + [RangeConstraint(IsImmediate = false, SkipOnTransactionCommit = true, Min = 10, Max = 20)] + public long LongField { get; set; } + } - [HierarchyRoot] - public class RegexTestEntity : BaseEntity - { - [Field] - [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = false, SkipOnTransactionCommit = true)] - public string StringField { get; set; } - } + [HierarchyRoot] + public class RegexTestEntity4 : BaseEntity + { + [Field] + [RegexConstraint("\b[A-Z][A-Z0-9]+\b", IsImmediate = false, SkipOnTransactionCommit = true)] + public string StringField { get; set; } } + + #endregion } From 328f039a98a68aa04f69ce45b1563fd7fd26fa9c Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 5 May 2021 18:08:49 +0500 Subject: [PATCH 59/71] Make some tests be compatible with Oracle - some tests cases were ignored due to Oracle particularities - some broken test were fixed in order to fit Oracle limitations --- .../Storage/IgnoreRulesValidateTest.cs | 28 +- .../Storage/NewProfilesTest.cs | 3 + .../Storage/SkippingValidationOnCommitTest.cs | 9 + .../Upgrade/ColumnTypeTest.cs | 278 +++++++++--------- 4 files changed, 160 insertions(+), 158 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs index 111ea8460f..3e59f6ac32 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/IgnoreRulesValidateTest.cs @@ -371,13 +371,13 @@ public void IgnoreReferencedTableTest() if (createConstraintsWithTable) { var delayedOp = CreateTableDelayed(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyLocally(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); - CreateForeignKeyLocally(catalog, schema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateForeignKeyLocally(catalog, schema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntityMyEntity2Id"); delayedOp(); } else { CreateTable(catalog, schema, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyInDb(catalog, schema, "MyIgnoredEntity", "Id", "PK_MyIgnoredEntity_Id"); - CreateForeignKeyInDb(catalog, schema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateForeignKeyInDb(catalog, schema, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntityMyEntity2Id"); } var ignoreRules = new IgnoreRuleCollection(); @@ -608,7 +608,7 @@ public void UpgradeDomainWithIgnoreRuleByMaskInPerformSafelyModeTest() [Test] public void MultischemaValidateTest() { - Require.AllFeaturesSupported(ProviderFeatures.Multischema | ProviderFeatures.Multidatabase); + Require.AllFeaturesSupported(ProviderFeatures.Multischema); SetMultischema(); @@ -620,13 +620,13 @@ public void MultischemaValidateTest() catalog = GetCatalog(); CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); - CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEnt2MyEnt1MyEnt1Id"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntityMyEntity2Id"); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); @@ -670,7 +670,7 @@ public void MultidatabaseValidateTest() [Test] public void MultischemaUpgrageInPerformModeTest() { - Require.AllFeaturesSupported(ProviderFeatures.Multischema | ProviderFeatures.Multidatabase); + Require.AllFeaturesSupported(ProviderFeatures.Multischema); SetMultischema(); @@ -681,13 +681,13 @@ public void MultischemaUpgrageInPerformModeTest() catalog = GetCatalog(); CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); - CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEnt2MyEnt1MyEnt1Id"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntityMyEntity2Id"); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); @@ -707,7 +707,7 @@ public void MultischemaUpgrageInPerformModeTest() [Test] public void MultischemaUpgrageInPerformSafelyModeTest() { - Require.AllFeaturesSupported(ProviderFeatures.Multischema | ProviderFeatures.Multidatabase); + Require.AllFeaturesSupported(ProviderFeatures.Multischema); SetMultischema(); @@ -718,13 +718,13 @@ public void MultischemaUpgrageInPerformSafelyModeTest() catalog = GetCatalog(); CreateColumn(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", GetTypeForInteger(SqlType.Int64)); - CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEntity2_MyEntity1_MyEntity1ID"); + CreateForeignKeyInDb(catalog, Schema2, "MyEntity2", "ReferencedIgnoredColumn", "MyEntity1", "Id", "FK_MyEnt2MyEnt1MyEnt1Id"); var addedColumnsNames = new[] { "Id", "FirstColumn", "MyEntity2Id" }; var addedColumnsTypes = new[] { GetTypeForInteger(SqlType.Int32), GetTypeForInteger(SqlType.Int64), GetTypeForInteger(SqlType.Int64) }; CreateTable(catalog, Schema2, "MyIgnoredEntity", addedColumnsNames, addedColumnsTypes); CreatePrimaryKeyInDb(catalog, Schema2, "MyIgnoredEntity", "Id", "PK_MyIgnoreTable_Id"); - CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntity_MyEntity2_Id"); + CreateForeignKeyInDb(catalog, Schema2, "MyIgnoredEntity", "MyEntity2Id", "MyEntity2", "Id", "FK_MyIgnoredEntityMyEntity2Id"); var ignoreRules = new IgnoreRuleCollection(); _ = ignoreRules.IgnoreColumn("ReferencedIgnoredColumn").WhenSchema(Schema2); @@ -835,6 +835,7 @@ private Domain BuildComplexDomain(DomainUpgradeMode mode, IgnoreRuleCollection i foreach (var type in secondPartTypes) { config.MappingRules.Map(type.Assembly, type.Namespace).ToSchema(Schema2); } + config.DefaultSchema = defaultSchema; } else if (isMultidatabaseTest) { foreach (var type in firstPartTypes) { @@ -844,11 +845,10 @@ private Domain BuildComplexDomain(DomainUpgradeMode mode, IgnoreRuleCollection i foreach (var type in secondPartTypes) { config.MappingRules.Map(type.Assembly, type.Namespace).ToDatabase(Multimapping.MultidatabaseTest.Database2Name); } + config.DefaultSchema = defaultSchema; + config.DefaultDatabase = GetConnectionInfo().ConnectionUrl.GetDatabase(); } - config.DefaultSchema = defaultSchema; - config.DefaultDatabase = GetConnectionInfo().ConnectionUrl.GetDatabase(); - foreach (var type in firstPartTypes.Union(secondPartTypes)) { config.Types.Register(type.Assembly, type.Namespace); } diff --git a/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs index 1bb3485d1e..f09a43aca4 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/NewProfilesTest.cs @@ -11,6 +11,7 @@ using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Internals; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Storage.NewClientProfileTestModel; namespace Xtensive.Orm.Tests.Storage.NewClientProfileTestModel @@ -790,6 +791,8 @@ public void ServerProfileCancelingOfEntitySetChanges() [Test] public void ClientProfileVersionsTest() { + Require.ProviderIsNot(StorageProvider.Oracle, "ExecuteNonQuery returns -1 all the time so versioning is not working"); + var sessionConfiguration = new SessionConfiguration(SessionOptions.ClientProfile | SessionOptions.AutoActivation | SessionOptions.ValidateEntityVersions); using (var session = Domain.OpenSession(sessionConfiguration)) { diff --git a/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs index b2d56e022d..5b5b7ab428 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SkippingValidationOnCommitTest.cs @@ -13,6 +13,7 @@ using Xtensive.Orm.Tests.Model.Association; using Xtensive.Orm.Validation; using Xtensive.Orm.Tests.Storage.SkippingValidationOnCommitTestModel; +using Xtensive.Orm.Providers; namespace Xtensive.Orm.Tests.Storage { @@ -527,6 +528,8 @@ public void LenghtConstraintNotImmediateSkippedTest() [Test] public void NotEmptyConstraintImmediateNotSkippedTest() { + Require.AllFeaturesNotSupported(ProviderFeatures.TreatEmptyStringAsNull); + using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entity = session.Query.All().First(); @@ -563,6 +566,8 @@ public void NotEmptyConstraintImmediateNotSkippedTest() [Test] public void NotEmptyConstraintImmediateSkippedTest() { + Require.AllFeaturesNotSupported(ProviderFeatures.TreatEmptyStringAsNull); + using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entity = session.Query.All().First(); @@ -597,6 +602,8 @@ public void NotEmptyConstraintImmediateSkippedTest() [Test] public void NotEmptyConstraintNotImmidiateNotSkippedTest() { + Require.AllFeaturesNotSupported(ProviderFeatures.TreatEmptyStringAsNull); + using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entity = session.Query.All().First(); @@ -633,6 +640,8 @@ public void NotEmptyConstraintNotImmidiateNotSkippedTest() [Test] public void NotEmptyConstraintNotImmediateSkippedTest() { + Require.AllFeaturesNotSupported(ProviderFeatures.TreatEmptyStringAsNull); + using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entity = session.Query.All().First(); diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs index b7b3de938e..a99b4942b7 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Ivan Galkin // Created: 2009.06.04 @@ -32,23 +32,22 @@ public class ColumnTypeTest public void SetUp() { BuildDomain(Mode.Recreate); - using (domain.OpenSession()) { - using (var t = Session.Current.OpenTransaction()) { - var x = new X { - FInt = 1, - FInt2 = 12345, - FLong = (long) int.MaxValue + 12345, - FLong2 = 12345, - FBool = true, - FString1 = "a", - FString5 = "12345", - FNotNullableString = "str", - FNullableDecimal = 123, - FGuid = new Guid("E484EE28-3801-445B-9DF0-FBCBE5AA4883"), - FDecimal = new decimal(1.2), - }; - t.Complete(); - } + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var x = new X { + FInt = 1, + FInt2 = 12345, + FLong = (long) int.MaxValue + 12345, + FLong2 = 12345, + FBool = true, + FString1 = "a", + FString5 = "12345", + FNotNullableString = "str", + FNullableDecimal = 123, + FGuid = new Guid("E484EE28-3801-445B-9DF0-FBCBE5AA4883"), + FDecimal = new decimal(1.2), + }; + t.Complete(); } } @@ -58,18 +57,14 @@ public void ValidateModeTest() AssertEx.Throws(() => ChangeFieldTypeTest("FInt", typeof (string), "1", Mode.Validate, null, null, null)); } - + [Test] - public void Int32ToStringTest() - { - ChangeFieldTypeTest("FInt", typeof (string), "1", Mode.Perform, null, null, null); - } + public void Int32ToStringTest() => + ChangeFieldTypeTest("FInt", typeof(string), "1", Mode.Perform, null, null, null); [Test] - public void Int32ToStringSafelyTest() - { - ChangeFieldTypeTest("FInt", typeof (string), "1", Mode.PerformSafely, null, null, null); - } + public void Int32ToStringSafelyTest() => + ChangeFieldTypeTest("FInt", typeof(string), "1", Mode.PerformSafely, null, null, null); [Test] public void Int32ToShortStringTest() @@ -81,18 +76,18 @@ public void Int32ToShortStringTest() [Test] public void Int32ToShortStringSafelyTest() { - if (ignoreColumnPrecision) + if (ignoreColumnPrecision) { ChangeFieldTypeTest("FInt2", typeof (string), "12345", Mode.PerformSafely, 3, null, null); - else + } + else { AssertEx.Throws(() => ChangeFieldTypeTest("FInt2", typeof (string), null, Mode.PerformSafely, 3, null, null)); + } } [Test] - public void StringToInt32Test() - { - ChangeFieldTypeTest("FString1", typeof (int), 0, Mode.Perform, null, null, null); - } + public void StringToInt32Test() => + ChangeFieldTypeTest("FString1", typeof(int), 0, Mode.Perform, null, null, null); [Test] public void StringToInt32SafelyTest() @@ -119,24 +114,22 @@ public void StringToShortStringTest() [Test] public void StringToShortStringSafelyTest() { - if (ignoreColumnPrecision) + if (ignoreColumnPrecision) { ChangeFieldTypeTest("FString5", typeof (string), "12345", Mode.PerformSafely, 3, null, null); - else + } + else { AssertEx.Throws(() => ChangeFieldTypeTest("FString5", typeof (string), string.Empty, Mode.PerformSafely, 3, null, null)); + } } [Test] - public void StringToLongStringTest() - { - ChangeFieldTypeTest("FString1", typeof (string), "a", Mode.Perform, 3, null, null); - } + public void StringToLongStringTest() => + ChangeFieldTypeTest("FString1", typeof(string), "a", Mode.Perform, 3, null, null); [Test] - public void StringToLongStringSafelyTest() - { - ChangeFieldTypeTest("FString1", typeof (string), "a", Mode.PerformSafely, 3, null, null); - } + public void StringToLongStringSafelyTest() => + ChangeFieldTypeTest("FString1", typeof(string), "a", Mode.PerformSafely, 3, null, null); [Test] public void BoolToStringTest() @@ -148,49 +141,41 @@ public void BoolToStringTest() [Test] public void BoolToStringSafelyTest() { - if (canConvertBoolToString) + if (canConvertBoolToString) { ChangeFieldTypeTest("FBool", typeof (string), "1", Mode.PerformSafely, 100, null, null); - else + } + else { AssertEx.Throws(() => ChangeFieldTypeTest("FBool", typeof (string), string.Empty, Mode.PerformSafely, 100, null, null)); + } } [Test] - public void Int32ToInt64Test() - { - ChangeFieldTypeTest("FInt2", typeof (long), 12345L, Mode.Perform, null, null, null); - } + public void Int32ToInt64Test() => + ChangeFieldTypeTest("FInt2", typeof(long), 12345L, Mode.Perform, null, null, null); [Test] - public void Int32ToInt64SafelyTest() - { - ChangeFieldTypeTest("FInt2", typeof (long), 12345L, Mode.PerformSafely, null, null, null); - } + public void Int32ToInt64SafelyTest() => + ChangeFieldTypeTest("FInt2", typeof(long), 12345L, Mode.PerformSafely, null, null, null); [Test] - public void Int64ToInt32Test() - { - ChangeFieldTypeTest("FLong", typeof (int), 0, Mode.Perform, null, null, null); - } + public void Int64ToInt32Test() => + ChangeFieldTypeTest("FLong", typeof(int), 0, Mode.Perform, null, null, null); [Test] public void Int64ToInt32SafelyTest() { - AssertEx.Throws(() => + _ = Assert.Throws(() => ChangeFieldTypeTest("FLong", typeof (int), 12345, Mode.PerformSafely, null, null, null)); } [Test] - public void DecimalToLongDecimalTest() - { - ChangeFieldTypeTest("FDecimal", typeof (decimal), new decimal(1.2), Mode.Perform, null, 3, 2); - } + public void DecimalToLongDecimalTest() => + ChangeFieldTypeTest("FDecimal", typeof(decimal), new decimal(1.2), Mode.Perform, null, 3, 2); [Test] - public void DecimalToLongDecimalSafelyTest() - { - ChangeFieldTypeTest("FDecimal", typeof (decimal), new decimal(1.2), Mode.PerformSafely, null, 3, 2); - } + public void DecimalToLongDecimalSafelyTest() => + ChangeFieldTypeTest("FDecimal", typeof(decimal), new decimal(1.2), Mode.PerformSafely, null, 3, 2); [Test] public void DecimalToShortDecimalTest() @@ -202,30 +187,26 @@ public void DecimalToShortDecimalTest() [Test] public void DecimalToShortDecimalSafelyTest() { - if (ignoreColumnPrecision) + if (ignoreColumnPrecision) { ChangeFieldTypeTest("FDecimal", typeof (decimal), new decimal(1.2), Mode.PerformSafely, null, 2, 0); - else + } + else { AssertEx.Throws(() => ChangeFieldTypeTest("FDecimal", typeof (decimal), new decimal(1.2), Mode.PerformSafely, null, 2, 0)); + } } [Test] - public void DecimalToNullableDecimalSafelyTest() - { - ChangeFieldTypeTest("FDecimal", typeof (decimal?), new decimal(1.2), Mode.PerformSafely, null, 2, 1); - } + public void DecimalToNullableDecimalSafelyTest() => + ChangeFieldTypeTest("FDecimal", typeof(decimal?), new decimal(1.2), Mode.PerformSafely, null, 2, 1); [Test] - public void DecimalToNullableDecimalTest() - { - ChangeFieldTypeTest("FDecimal", typeof (decimal?), new decimal(1.2), Mode.Perform, null, 2, 1); - } + public void DecimalToNullableDecimalTest() => + ChangeFieldTypeTest("FDecimal", typeof(decimal?), new decimal(1.2), Mode.Perform, null, 2, 1); [Test] - public void NullableDecimalToDecimalTest() - { + public void NullableDecimalToDecimalTest() => ChangeFieldTypeTest("FNullableDecimal", typeof(decimal), new decimal(123), Mode.Perform, null, null, null); - } [Test] public void NullableDecimalToDecimalSafelyTest() @@ -235,26 +216,24 @@ public void NullableDecimalToDecimalSafelyTest() } [Test] - public void StringToNullableStringSafelyTest() - { + public void StringToNullableStringSafelyTest() => ChangeFieldTypeTest("FNotNullableString", typeof(string), "str", Mode.PerformSafely, null, null, null); - } [Test] - public void StringToNullableStringTest() - { + public void StringToNullableStringTest() => ChangeFieldTypeTest("FNotNullableString", typeof(string), "str", Mode.Perform, null, null, null); - } [Test] public void NullableStringToStringTest() { + Require.AllFeaturesNotSupported(ProviderFeatures.TreatEmptyStringAsNull); ChangeFieldTypeTest("FString1", typeof (string), "a", Mode.Perform, 1, null, null, false); } [Test] public void NullableStringToStringSafelyTest() { + Require.AllFeaturesNotSupported(ProviderFeatures.TreatEmptyStringAsNull); AssertEx.Throws(() => ChangeFieldTypeTest("FString1", typeof (string), "a", Mode.PerformSafely, 1, null, null, false)); } @@ -263,72 +242,78 @@ public void NullableStringToStringSafelyTest() [Test] public void AddNonNullableColumnTest() { - AddFieldTest(typeof (Guid)); - AddFieldTest(typeof (bool)); - AddFieldTest(typeof (int)); - AddFieldTest(typeof (long)); - AddFieldTest(typeof (float)); - AddFieldTest(typeof (TimeSpan)); - AddFieldTest(typeof (DateTime)); + AddFieldTest(typeof(Guid), Guid.Empty); + AddFieldTest(typeof(bool)); + AddFieldTest(typeof(int)); + AddFieldTest(typeof(long)); + AddFieldTest(typeof(float)); + AddFieldTest(typeof(TimeSpan)); + AddFieldTest(typeof(DateTime)); } #region Helper methods private void BuildDomain(DomainUpgradeMode upgradeMode) { - if (domain != null) + if (domain != null) { domain.DisposeSafely(); + } + var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = upgradeMode; - configuration.Types.Register(typeof (X)); - configuration.Types.Register(typeof (TestUpgrader)); - configuration.Types.Register(typeof (FieldTypeChanger)); - ConfigureStorageTraits(configuration); + configuration.Types.Register(typeof(X)); + configuration.Types.Register(typeof(TestUpgrader)); + configuration.Types.Register(typeof(FieldTypeChanger)); + ConfigureStorageTraits(); domain = Domain.Build(configuration); } - private void ConfigureStorageTraits(DomainConfiguration configuration) + private void ConfigureStorageTraits() { - var provider = configuration.ConnectionInfo.Provider; + var providerInfo = StorageProviderInfo.Instance; - canConvertBoolToString = provider - .In(WellKnown.Provider.Firebird, WellKnown.Provider.Sqlite); + canConvertBoolToString = providerInfo + .CheckProviderIs(StorageProvider.Firebird | StorageProvider.Sqlite | StorageProvider.Oracle); - ignoreColumnPrecision = provider - .In(WellKnown.Provider.Sqlite); + ignoreColumnPrecision = providerInfo + .CheckProviderIs(StorageProvider.Sqlite); } - private void ChangeFieldTypeTest(string fieldName, Type newColumnType, object expectedValue, DomainUpgradeMode mode, int? newLength, int? newPresicion, int? newScale) - { + private void ChangeFieldTypeTest( + string fieldName, Type newColumnType, object expectedValue, + DomainUpgradeMode mode, int? newLength, int? newPresicion, int? newScale) => ChangeFieldTypeTest(fieldName, newColumnType, expectedValue, mode, newLength, newPresicion, newScale, null); - } - private void ChangeFieldTypeTest(string fieldName, Type newColumnType, object expectedValue, DomainUpgradeMode mode, int? newLength, int? newPrecision, int? newScale, bool? isNullable) + private void ChangeFieldTypeTest( + string fieldName, Type newColumnType, object expectedValue, + DomainUpgradeMode mode, int? newLength, int? newPrecision, int? newScale, bool? isNullable) { using (FieldTypeChanger.Enable(newColumnType, fieldName, newLength, newPrecision, newScale, isNullable)) { BuildDomain(mode); } - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var x = session.Query.All().First(); - Assert.AreEqual(expectedValue, x[fieldName]); - } + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var x = session.Query.All().First(); + Assert.AreEqual(expectedValue, x[fieldName]); } } - private void AddFieldTest(Type newColumnType) + private void AddFieldTest(Type newColumnType, object defaultValue = null) { SetUp(); - if (domain != null) + if (domain != null) { domain.DisposeSafely(); + } + var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Perform; - configuration.Types.Register(typeof (X)); - configuration.Types.Register(typeof (TestUpgrader)); - configuration.Types.Register(typeof (FieldTypeChanger)); - configuration.Types.Register(typeof (AddColumnBuilder)); + configuration.Types.Register(typeof(X)); + configuration.Types.Register(typeof(TestUpgrader)); + configuration.Types.Register(typeof(FieldTypeChanger)); + configuration.Types.Register(typeof(AddColumnBuilder)); AddColumnBuilder.NewColumnType = newColumnType; + AddColumnBuilder.DefaultValue = defaultValue; AddColumnBuilder.IsEnabled = true; domain = Domain.Build(configuration); } @@ -390,8 +375,10 @@ public class FieldTypeChanger : IModule /// Handler is already enabled. public static IDisposable Enable(Type newType, string fieldName, int? length, int? precision, int? scale, bool? isNullable) { - if (isEnabled) + if (isEnabled) { throw new InvalidOperationException(); + } + isEnabled = true; ColumnType = newType; ColumnName = fieldName; @@ -413,8 +400,9 @@ public virtual void OnBuilt(Domain domain) public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) { - if (!isEnabled || !model.Types.Contains("X")) + if (!isEnabled || !model.Types.Contains("X")) { return; + } var xType = model.Types["X"]; var oldFieled = xType.Fields[ColumnName]; @@ -423,9 +411,10 @@ public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) newField.Scale = ColumnScale; newField.Precision = ColumnPrecision; newField.Name = oldFieled.Name; - if (ColumnNullable != null) + if (ColumnNullable != null) { newField.IsNullable = ColumnNullable.Value; - xType.Fields.Remove(oldFieled); + } + _ = xType.Fields.Remove(oldFieled); xType.Fields.Add(newField); } @@ -437,20 +426,27 @@ public class AddColumnBuilder : IModule public static Type NewColumnType { get; set; } + public static object DefaultValue { get; set; } + public void OnBuilt(Domain domain) { } public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) { - if (!IsEnabled) + if (!IsEnabled) { return; - if (!model.Types.Contains("X")) + } + if (!model.Types.Contains("X")) { return; - + } + var xType = model.Types["X"]; var newField = new FieldDef(NewColumnType, context.Validator); newField.Name = "NewColumn"; + if (DefaultValue != null) { + newField.DefaultValue = DefaultValue; + } xType.Fields.Add(newField); } } @@ -464,8 +460,10 @@ public class TestUpgrader : UpgradeHandler /// Handler is already enabled. public static IDisposable Enable(UpgradeHint hint) { - if (isEnabled) + if (isEnabled) { throw new InvalidOperationException(); + } + isEnabled = true; columnHint = hint; return new Disposable(_ => { @@ -474,28 +472,20 @@ public static IDisposable Enable(UpgradeHint hint) }); } - public override bool IsEnabled { get { return isEnabled; } } - - protected override string DetectAssemblyVersion() - { - return "1"; - } + public override bool IsEnabled => isEnabled; - public override bool CanUpgradeFrom(string oldVersion) - { - return true; - } + protected override string DetectAssemblyVersion() => "1"; + + public override bool CanUpgradeFrom(string oldVersion) => true; protected override void AddUpgradeHints(ISet hints) { - if (columnHint!=null) - hints.Add(columnHint); + if (columnHint!=null) { + _ = hints.Add(columnHint); + } } - public override bool IsTypeAvailable(Type type, UpgradeStage upgradeStage) - { - return true; - } + public override bool IsTypeAvailable(Type type, UpgradeStage upgradeStage) => true; } } From 93b42454e0dea7c7c0ffbc188805cc79e058ce5c Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 5 May 2021 18:21:55 +0500 Subject: [PATCH 60/71] Important! Change NULLs behavior in ORDER BY clause The rest of storages have nulls order similar to .NET ordering algorithm so now Oracle v11 and above have the same order as .NET --- .../Sql.Drivers.Oracle/v11/Translator.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs index 0636341df4..e9b02b83d9 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs @@ -7,6 +7,7 @@ using System; using Xtensive.Sql.Compiler; using Xtensive.Sql.Ddl; +using Xtensive.Sql.Dml; namespace Xtensive.Sql.Drivers.Oracle.v11 { @@ -32,6 +33,14 @@ public override string Translate(SqlCompilerContext context, SqlCreateIndex node return base.Translate(context, node, section); } + public override string Translate(SqlCompilerContext context, SqlOrder node, NodeSection section) + { + if (section == NodeSection.Exit) { + return node.Ascending ? "ASC NULLS FIRST" : "DESC NULLS LAST"; + } + return string.Empty; + } + public override string Translate(SqlValueType type) { // we need to explicitly specify maximum interval precision From 3114ccb914f0d514dec5ad8d4ce1bd6787d8f85d Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 6 May 2021 16:59:47 +0500 Subject: [PATCH 61/71] Oracle now correctly handles equality operator for byte[] fields --- .../Issues/Issue0587_ByteArrayEquals.cs | 66 ++++---- .../ExpressionProcessor.Helpers.cs | 86 ++++++---- .../Expressions/ExpressionProcessor.cs | 150 ++++++++++-------- 3 files changed, 166 insertions(+), 136 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs index 34774614bb..affb479845 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2010-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2010.01.22 @@ -8,14 +8,12 @@ using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; -using Xtensive.Orm.Tests.Issues.Xtensive.Storage.Tests.Issues.Issue0587_ByteArrayEquals_Model; +using Xtensive.Orm.Tests.Issues.Issue0587_ByteArrayEquals_Model; namespace Xtensive.Orm.Tests.Issues { - namespace Xtensive.Storage.Tests.Issues.Issue0587_ByteArrayEquals_Model + namespace Issue0587_ByteArrayEquals_Model { - // [Index("Name", Unique = true)] - // [Index("UniqueIndentifier", Unique = true)] [HierarchyRoot] public class User : Entity { @@ -34,28 +32,6 @@ public class User : Entity [Serializable] public class Issue0587_ByteArrayEquals : AutoBuildTest { - public override void TestFixtureSetUp() - { - base.TestFixtureSetUp(); - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - Fill(); - t.Complete(); - } - } - } - - private void Fill() - { - for (byte i = 0; i < 10; i++) { - var user = new User { - Name = string.Format("name_{0}", i), - Photo = new byte[] {i, i, i} - }; - } - Session.Current.SaveChanges(); - } - protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); @@ -63,19 +39,31 @@ protected override DomainConfiguration BuildConfiguration() return config; } + protected override void PopulateData() + { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + for (byte i = 0; i < 10; i++) { + _ = new User { + Name = string.Format("name_{0}", i), + Photo = new byte[] { i, i, i } + }; + } + t.Complete(); + } + } + [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - int pageIndex = 1; - int pageSize = 1; - var usersQuery = session.Query.All().Skip(pageIndex * pageSize).Take(pageSize); - var key = new byte[]{1,1,1}; - var query = session.Query.All().Where(user => user.Photo==key); - var result = query.ToList(); - Assert.Greater(result.Count, 0); - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + int pageIndex = 1; + int pageSize = 1; + var usersQuery = session.Query.All().Skip(pageIndex * pageSize).Take(pageSize); + var key = new byte[] { 1, 1, 1 }; + var result = session.Query.All().Where(user => user.Photo == key).ToList(); + Assert.Greater(result.Count, 0); } } } diff --git a/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.Helpers.cs b/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.Helpers.cs index 64351a8f5c..49cc1b674d 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.Helpers.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.Helpers.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 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 // Created: 2009.09.26 @@ -17,6 +17,15 @@ namespace Xtensive.Orm.Providers { partial class ExpressionProcessor { + private readonly static Type ObjectType = typeof(object); + private readonly static Type BooleanType = typeof(bool); + private readonly static Type Int32Type = typeof(int); + private readonly static Type CharType = typeof(char); + + private readonly static Type DateTimeType = typeof(DateTime); + private readonly static Type DateTimeOffsetType = typeof(DateTimeOffset); + private readonly static Type ParameterType = typeof(Parameter); + private SqlExpression TryTranslateCompareExpression(BinaryExpression expression) { bool isGoodExpression = @@ -178,6 +187,19 @@ private SqlExpression TryTranslateInequalitySpecialCases(SqlExpression left, Sql return null; } + private (SqlExpression right, SqlExpression left) BuildByteArraySyntaxComparison(SqlExpression left, SqlExpression right) + { + var newLeft = (SqlExpression) SqlDml.Literal(0); + var newRight = OracleBlobCompare(left, right); + + return (newLeft, newRight); + } + + private static SqlExpression OracleBlobCompare(SqlExpression left, SqlExpression right) + { + return SqlDml.FunctionCall("dbms_lob.compare", left, right); + } + private SqlExpression CompileMember(MemberInfo member, SqlExpression instance, params SqlExpression[] arguments) { var memberCompiler = memberCompilerProvider.GetCompiler(member); @@ -185,33 +207,30 @@ private SqlExpression CompileMember(MemberInfo member, SqlExpression instance, p throw new NotSupportedException(string.Format(Strings.ExMemberXIsNotSupported, member.GetFullName(true))); return memberCompiler.Invoke(instance, arguments); } - + private static bool IsCharToIntConvert(Expression e) { return - e.NodeType==ExpressionType.Convert && - e.Type==typeof (int) && - ((UnaryExpression) e).Operand.Type==typeof (char); + e.NodeType == ExpressionType.Convert && + e.Type == Int32Type && + ((UnaryExpression) e).Operand.Type == CharType; } - private static bool IsIntConstant(Expression expression) - { - return expression.NodeType==ExpressionType.Constant && expression.Type==typeof (int); - } + private static bool IsIntConstant(Expression expression) => + expression.NodeType == ExpressionType.Constant && expression.Type == Int32Type; - private static bool IsBooleanExpression(Expression expression) - { - return StripObjectCasts(expression).Type.StripNullable()==typeof (bool); - } + private static bool IsBooleanExpression(Expression expression) => + IsExpressionOf(expression, BooleanType); - private static bool IsDateTimeExpression(Expression expression) - { - return StripObjectCasts(expression).Type.StripNullable()==typeof (DateTime); - } + private static bool IsDateTimeExpression(Expression expression) => + IsExpressionOf(expression, DateTimeType); + + private static bool IsDateTimeOffsetExpression(Expression expression) => + IsExpressionOf(expression, DateTimeOffsetType); - private static bool IsDateTimeOffsetExpression(Expression expression) + private static bool IsExpressionOf(Expression expression, Type type) { - return StripObjectCasts(expression).Type.StripNullable()==typeof (DateTimeOffset); + return StripObjectCasts(expression).Type.StripNullable() == type; } private static bool IsComparisonExpression(Expression expression) @@ -227,8 +246,9 @@ private static bool IsComparisonExpression(Expression expression) private static Expression StripObjectCasts(Expression expression) { - while (expression.Type==typeof (object) && expression.NodeType==ExpressionType.Convert) + while (expression.Type == ObjectType && expression.NodeType == ExpressionType.Convert) { expression = GetOperand(expression); + } return expression; } @@ -262,33 +282,37 @@ private QueryParameterIdentity GetParameterIdentity(TypeMapping mapping, var expression = accessor.Body; // Strip cast to object - if (expression.NodeType==ExpressionType.Convert) + if (expression.NodeType == ExpressionType.Convert) { expression = ((UnaryExpression) expression).Operand; + } // Check for closure member access - if (expression.NodeType!=ExpressionType.MemberAccess) + if (expression.NodeType != ExpressionType.MemberAccess) { return null; + } var memberAccess = (MemberExpression) expression; var operand = memberAccess.Expression; - if (operand==null || !operand.Type.IsClosure()) + if (operand == null || !operand.Type.IsClosure()) { return null; + } + var fieldName = memberAccess.Member.Name; // Check for raw closure - if (operand.NodeType==ExpressionType.Constant) { + if (operand.NodeType == ExpressionType.Constant) { var closureObject = ((ConstantExpression) operand).Value; return new QueryParameterIdentity(mapping, closureObject, fieldName, bindingType); } // Check for parameterized closure - if (operand.NodeType==ExpressionType.MemberAccess) { + if (operand.NodeType == ExpressionType.MemberAccess) { memberAccess = (MemberExpression) operand; operand = memberAccess.Expression; - var isParameter = operand!=null - && operand.NodeType==ExpressionType.Constant - && typeof (Parameter).IsAssignableFrom(operand.Type) - && memberAccess.Member.Name=="Value"; + var isParameter = operand != null + && operand.NodeType == ExpressionType.Constant + && ParameterType.IsAssignableFrom(operand.Type) + && memberAccess.Member.Name == "Value"; if (isParameter) { var parameterObject = ((ConstantExpression) operand).Value; return new QueryParameterIdentity(mapping, parameterObject, fieldName, bindingType); diff --git a/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.cs b/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.cs index d360fb155c..fc50bf5519 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/Expressions/ExpressionProcessor.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kochetov // Created: 2008.09.05 @@ -45,6 +45,7 @@ private readonly Dictionary bindi private readonly bool emptyStringIsNull; private readonly bool dateTimeEmulation; private readonly bool dateTimeOffsetEmulation; + private readonly bool specialByteArrayComparison; private readonly ProviderInfo providerInfo; private bool executed; @@ -164,19 +165,20 @@ private SqlExpression VisitCast(UnaryExpression cast, SqlExpression operand) protected override SqlExpression VisitBinary(BinaryExpression expression) { // handle x.CompareTo(y) > 0 and similar comparisons - SqlExpression result = TryTranslateCompareExpression(expression); - if (!result.IsNullReference()) + var result = TryTranslateCompareExpression(expression); + if (!result.IsNullReference()) { return result; + } SqlExpression left; SqlExpression right; - bool isEqualityCheck = - expression.NodeType==ExpressionType.Equal - || expression.NodeType==ExpressionType.NotEqual; + var isEqualityCheck = + expression.NodeType == ExpressionType.Equal + || expression.NodeType == ExpressionType.NotEqual; - bool isBooleanFixRequired = fixBooleanExpressions - && (isEqualityCheck || expression.NodeType==ExpressionType.Coalesce) + var isBooleanFixRequired = fixBooleanExpressions + && (isEqualityCheck || expression.NodeType == ExpressionType.Coalesce) && (IsBooleanExpression(expression.Left) || IsBooleanExpression(expression.Right)); if (IsCharToIntConvert(expression.Left) && IsCharToIntConvert(expression.Right)) { @@ -194,7 +196,7 @@ protected override SqlExpression VisitBinary(BinaryExpression expression) left = ConvertIntConstantToSingleCharString(expression.Left); right = Visit(GetOperand(expression.Right), isEqualityCheck); } - else { + else { // regular case left = Visit(expression.Left, isEqualityCheck); right = Visit(expression.Right, isEqualityCheck); @@ -203,10 +205,12 @@ protected override SqlExpression VisitBinary(BinaryExpression expression) // boolean expressions should be compared as integers. // additional check is required because some type information might be lost. // we assume they already have correct format in that case. - if (IsBooleanExpression(expression.Left)) + if (IsBooleanExpression(expression.Left)) { left = booleanExpressionConverter.BooleanToInt(left); - if (IsBooleanExpression(expression.Right)) + } + if (IsBooleanExpression(expression.Right)) { right = booleanExpressionConverter.BooleanToInt(right); + } } //handle SQLite DateTime comparsion @@ -221,78 +225,91 @@ protected override SqlExpression VisitBinary(BinaryExpression expression) //handle SQLite DateTimeOffset comparsion if (dateTimeOffsetEmulation - && left.NodeType!=SqlNodeType.Null - && right.NodeType!=SqlNodeType.Null + && left.NodeType != SqlNodeType.Null + && right.NodeType != SqlNodeType.Null && IsComparisonExpression(expression) && (IsDateTimeOffsetExpression(expression.Left) || IsDateTimeOffsetExpression(expression.Right))) { left = SqlDml.Cast(left, SqlType.DateTimeOffset); right = SqlDml.Cast(right, SqlType.DateTimeOffset); } + //handle Oracle special syntax of BLOB comparison + if (specialByteArrayComparison + && (IsExpressionOf(expression.Left, typeof(byte[])) || IsExpressionOf(expression.Left, typeof(byte[])))) { + var comparison = BuildByteArraySyntaxComparison(left, right); + left = comparison.left; + right = comparison.right; + } + // handle special cases result = TryTranslateBinaryExpressionSpecialCases(expression, left, right); - if (!result.IsNullReference()) + if (!result.IsNullReference()) { return result; + } // handle overloaded operators - if (expression.Method!=null) + if (expression.Method != null) { return CompileMember(expression.Method, null, left, right); + } //handle wrapped enums - SqlContainer container = left as SqlContainer; - if (container!=null) + var container = left as SqlContainer; + if (container != null) { left = TryUnwrapEnum(container); + } container = right as SqlContainer; - if (container!=null) + if (container != null) { right = TryUnwrapEnum(container); + } switch (expression.NodeType) { - case ExpressionType.Add: - case ExpressionType.AddChecked: - return SqlDml.Add(left, right); - case ExpressionType.And: - return IsBooleanExpression(expression.Left) - ? SqlDml.And(left, right) - : SqlDml.BitAnd(left, right); - case ExpressionType.AndAlso: - return SqlDml.And(left, right); - case ExpressionType.Coalesce: - SqlExpression coalesce = SqlDml.Coalesce(left, right); - if (isBooleanFixRequired) - coalesce = booleanExpressionConverter.IntToBoolean(coalesce); - return coalesce; - case ExpressionType.Divide: - return SqlDml.Divide(left, right); - case ExpressionType.Equal: - return SqlDml.Equals(left, right); - case ExpressionType.ExclusiveOr: - return SqlDml.BitXor(left, right); - case ExpressionType.GreaterThan: - return SqlDml.GreaterThan(left, right); - case ExpressionType.GreaterThanOrEqual: - return SqlDml.GreaterThanOrEquals(left, right); - case ExpressionType.LessThan: - return SqlDml.LessThan(left, right); - case ExpressionType.LessThanOrEqual: - return SqlDml.LessThanOrEquals(left, right); - case ExpressionType.Modulo: - return SqlDml.Modulo(left, right); - case ExpressionType.Multiply: - case ExpressionType.MultiplyChecked: - return SqlDml.Multiply(left, right); - case ExpressionType.NotEqual: - return SqlDml.NotEquals(left, right); - case ExpressionType.Or: - return IsBooleanExpression(expression.Left) - ? SqlDml.Or(left, right) - : SqlDml.BitOr(left, right); - case ExpressionType.OrElse: - return SqlDml.Or(left, right); - case ExpressionType.Subtract: - case ExpressionType.SubtractChecked: - return SqlDml.Subtract(left, right); - default: - throw new ArgumentOutOfRangeException("expression"); + case ExpressionType.Add: + case ExpressionType.AddChecked: + return SqlDml.Add(left, right); + case ExpressionType.And: + return IsBooleanExpression(expression.Left) + ? SqlDml.And(left, right) + : SqlDml.BitAnd(left, right); + case ExpressionType.AndAlso: + return SqlDml.And(left, right); + case ExpressionType.Coalesce: + var coalesce = (SqlExpression) SqlDml.Coalesce(left, right); + if (isBooleanFixRequired) { + coalesce = booleanExpressionConverter.IntToBoolean(coalesce); + } + return coalesce; + case ExpressionType.Divide: + return SqlDml.Divide(left, right); + case ExpressionType.Equal: + return SqlDml.Equals(left, right); + case ExpressionType.ExclusiveOr: + return SqlDml.BitXor(left, right); + case ExpressionType.GreaterThan: + return SqlDml.GreaterThan(left, right); + case ExpressionType.GreaterThanOrEqual: + return SqlDml.GreaterThanOrEquals(left, right); + case ExpressionType.LessThan: + return SqlDml.LessThan(left, right); + case ExpressionType.LessThanOrEqual: + return SqlDml.LessThanOrEquals(left, right); + case ExpressionType.Modulo: + return SqlDml.Modulo(left, right); + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + return SqlDml.Multiply(left, right); + case ExpressionType.NotEqual: + return SqlDml.NotEquals(left, right); + case ExpressionType.Or: + return IsBooleanExpression(expression.Left) + ? SqlDml.Or(left, right) + : SqlDml.BitOr(left, right); + case ExpressionType.OrElse: + return SqlDml.Or(left, right); + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + return SqlDml.Subtract(left, right); + default: + throw new ArgumentOutOfRangeException("expression"); } } @@ -466,6 +483,7 @@ public ExpressionProcessor( dateTimeEmulation = providerInfo.Supports(ProviderFeatures.DateTimeEmulation); dateTimeOffsetEmulation = providerInfo.Supports(ProviderFeatures.DateTimeOffsetEmulation); memberCompilerProvider = handlers.DomainHandler.GetMemberCompilerProvider(); + specialByteArrayComparison = providerInfo.ProviderName.Equals(WellKnown.Provider.Oracle); bindings = new HashSet(); activeParameters = new List(); From 1f2f16fd39271e4cf633d1a50ed065970dd243b2 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 6 May 2021 18:30:44 +0500 Subject: [PATCH 62/71] Ignore test for Oracle due to lack of resolution needed --- .../Issues/Issue0818_NanosecondTrancation.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs index dd5f5db39a..d89cf2b601 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2010-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Dmitri Maximov // Created: 2010.10.14 @@ -42,7 +42,7 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - Require.ProviderIsNot(StorageProvider.PostgreSql); // PostgreSql stores intervals with microseconds only + Require.ProviderIsNot(StorageProvider.PostgreSql | StorageProvider.Oracle); // PostgreSql and Oracle store intervals with microseconds only long ticks = 123456789; From 59b8ba89999f67a1fa9be47b72401d2d9f51df71 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 6 May 2021 20:27:29 +0500 Subject: [PATCH 63/71] Oracle: simlplify some DateTimeOffset operations It also fixed some issues with these operations --- .../Sql.Drivers.Oracle/v09/Compiler.cs | 30 ++----------------- 1 file changed, 3 insertions(+), 27 deletions(-) diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Compiler.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Compiler.cs index f7bd2f0d1d..5e0f22a719 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Compiler.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Compiler.cs @@ -356,35 +356,13 @@ private static SqlExpression DateTimeOffsetExtractPart(SqlExpression dateTimeOff private static SqlExpression DateTimeOffsetToLocalDateTime(SqlExpression dateTimeOffset) { - return SqlDml.Cast( - SqlDml.DateTimePlusInterval( - DateTimeOffsetToUtcDateTime(dateTimeOffset), - SqlDml.DateTimeMinusDateTime( - DateTimeOffsetToUtcDateTime( - SqlDml.Native("SYSTIMESTAMP")), - SqlDml.Native("SYSTIMESTAMP"))), - SqlType.DateTime); + return SqlDml.Cast(DateTimeOffsetToLocalTime(dateTimeOffset), SqlType.DateTime); } private static SqlExpression DateTimeOffsetToLocalTime(SqlExpression dateTimeOffset) { - return SqlDml.FunctionCall("FROM_TZ", - SqlDml.Cast( - dateTimeOffset - - - (SysExtractUtc(SqlDml.Native("CURRENT_TIMESTAMP")) - - SysExtractUtc( - SqlDml.FunctionCall("FROM_TZ", - SqlDml.Cast(SqlDml.Native("CURRENT_TIMESTAMP"), SqlType.DateTime), - DateTimeOffsetExtractPart(dateTimeOffset, "TZR")))), - SqlType.DateTime) - , SqlDml.Native("sessiontimezone")); - } - - private static SqlExpression SysExtractUtc(SqlExpression dateTimeOffset) - { - return SqlDml.FunctionCall("SYS_EXTRACT_UTC", dateTimeOffset); + return SqlDml.RawConcat(dateTimeOffset, SqlDml.Native(" AT LOCAL")); } private static SqlExpression DateTimeToDateTimeOffset(SqlExpression dateTime) @@ -394,9 +372,7 @@ private static SqlExpression DateTimeToDateTimeOffset(SqlExpression dateTime) private static SqlExpression DateTimeOffsetToUtcTime(SqlExpression dateTimeOffset) { - return SqlDml.FunctionCall("FROM_TZ", - DateTimeOffsetToUtcDateTime(dateTimeOffset), - AnsiString("+00:00")); + return SqlDml.RawConcat(dateTimeOffset, SqlDml.Native(" at time zone 'UTC'")); } private static SqlExpression AnsiString(string value) From 894ac25487cb9609397967bcccae2d1550e38a9a Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 6 May 2021 20:43:07 +0500 Subject: [PATCH 64/71] Fix tests that fail on Oracle Basically they fail because they were written without oracle in mind. Some of them fail because of lack of feature check, others - because of bad design. --- ...ssueJira0221_UnableToTranslateAggregate.cs | 13 ++++--- ...ssueJira0240_SortingInSubqueryIsOmitted.cs | 35 ++++++++++--------- ...irstOrDefaultInSubqueryUsesWrongDefault.cs | 9 +++-- .../IssueJira0446_TypeAsOnSubqueryOperand.cs | 11 +++--- .../IssueJira0449_TimeSpanMinMaxValue.cs | 25 ++++++++----- .../IssueJira0471_LikeOperatorSupport.cs | 35 +++++++++---------- ...ra0627_PocoClassPropertyRenitialization.cs | 4 +-- ...a0643_OracleDateTimeOffsetExtractionBug.cs | 16 +++++---- 8 files changed, 85 insertions(+), 63 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0221_UnableToTranslateAggregate.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0221_UnableToTranslateAggregate.cs index 88100b8867..3acfb63bec 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0221_UnableToTranslateAggregate.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0221_UnableToTranslateAggregate.cs @@ -1,12 +1,13 @@ -// Copyright (C) 2011 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2021 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 // Created: 2011.11.21 using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Issues.IssueJira0221_UnableToTranslateAggregateModel; namespace Xtensive.Orm.Tests.Issues.IssueJira0221_UnableToTranslateAggregateModel @@ -55,10 +56,12 @@ public override void TestFixtureSetUp() CreateSessionAndTransaction(); - new ZamesInfo {Owner = new Zames(), Rank = 1}; - new ZamesInfo {Owner = new Zames(), Rank = 3}; + _ = new ZamesInfo {Owner = new Zames(), Rank = 1}; + _ = new ZamesInfo {Owner = new Zames(), Rank = 3}; } + protected override void CheckRequirements() => Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); + #region Min() [Test] diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0240_SortingInSubqueryIsOmitted.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0240_SortingInSubqueryIsOmitted.cs index b66d0930c7..7555d67d81 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0240_SortingInSubqueryIsOmitted.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0240_SortingInSubqueryIsOmitted.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2012 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2012-2021 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 // Created: 2012.01.25 @@ -8,6 +8,7 @@ using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Issues.IssueJira0240_SortingInSubqueryIsOmittedModel; namespace Xtensive.Orm.Tests.Issues.IssueJira0240_SortingInSubqueryIsOmittedModel @@ -43,18 +44,18 @@ public class IssueJira0240_SortingInSubqueryIsOmitted : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (Container).Assembly, typeof (Container).Namespace); + configuration.Types.Register(typeof(Container).Assembly, typeof(Container).Namespace); return configuration; } protected override void PopulateData() { - using (Domain.OpenSession()) - using (var tx = Session.Current.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { var c = new Container(); - new StoredContainer {Container = c, CreationTime = new DateTime(2012, 1, 1), Address = "1"}; - new StoredContainer {Container = c, CreationTime = new DateTime(2012, 1, 2), Address = "2"}; - new StoredContainer {Container = c, CreationTime = new DateTime(2012, 1, 3), Address = "3"}; + _ = new StoredContainer { Container = c, CreationTime = new DateTime(2012, 1, 1), Address = "1" }; + _ = new StoredContainer { Container = c, CreationTime = new DateTime(2012, 1, 2), Address = "2" }; + _ = new StoredContainer { Container = c, CreationTime = new DateTime(2012, 1, 3), Address = "3" }; tx.Complete(); } } @@ -62,13 +63,15 @@ protected override void PopulateData() [Test] public void MainTest() { - using (Domain.OpenSession()) - using (var tx = Session.Current.OpenTransaction()) { - var r = Query.All() + Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); + + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + var r = session.Query.All() .Select(c => new { c.Id, LastLocation = Query.All() - .Where(s => s.Container==c) + .Where(s => s.Container == c) .OrderByDescending(s => s.CreationTime) .Select(s => s.Address) .FirstOrDefault() @@ -84,10 +87,10 @@ public void RegressionTest() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - var container = Query.All().Single(); + var container = session.Query.All().Single(); var now = DateTime.Now; - var lastStoredContainer = Query.All() - .Where(s => s.Container==container && s.CreationTime <= now) + var lastStoredContainer = session.Query.All() + .Where(s => s.Container == container && s.CreationTime <= now) .GroupBy(s => s.CreationTime) .OrderByDescending(s => s.Key) .FirstOrDefault(); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0443_FirstOrDefaultInSubqueryUsesWrongDefault.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0443_FirstOrDefaultInSubqueryUsesWrongDefault.cs index c20aa6b0dc..abd1db497b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0443_FirstOrDefaultInSubqueryUsesWrongDefault.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0443_FirstOrDefaultInSubqueryUsesWrongDefault.cs @@ -1,12 +1,13 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 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 // Created: 2013.04.30 using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Issues.IssueJira0443_FirstOrDefaultInSubqueryUsesWrongDefaultModel; namespace Xtensive.Orm.Tests.Issues @@ -53,6 +54,8 @@ protected override DomainConfiguration BuildConfiguration() return configuration; } + protected override void CheckRequirements() => Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); + protected override void PopulateData() { using (var session = Domain.OpenSession()) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0446_TypeAsOnSubqueryOperand.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0446_TypeAsOnSubqueryOperand.cs index 24827d11ee..92df577b74 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0446_TypeAsOnSubqueryOperand.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0446_TypeAsOnSubqueryOperand.cs @@ -1,12 +1,13 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 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 // Created: 2013.06.25 using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Issues.IssueJira0446_TypeAsOnSubqueryOperandModel; namespace Xtensive.Orm.Tests.Issues @@ -46,10 +47,12 @@ public class IssueJira0446_TypeAsOnSubqueryOperand : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.Register(typeof (Owner).Assembly, typeof (Owner).Namespace); + configuration.Types.Register(typeof(Owner).Assembly, typeof(Owner).Namespace); return configuration; } + protected override void CheckRequirements() => Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); + [Test] public void MainTest() { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs index a11e6b4040..e016ebe473 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 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 // Created: 2013.07.02 @@ -36,17 +36,26 @@ protected override DomainConfiguration BuildConfiguration() } [Test] - public void MainTest() + public void MinTest() { + Require.ProviderIsNot(StorageProvider.Oracle, "Oracle has no resolution for TimeSpan.MinValue"); + using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { var created = new EntityWithTimeSpan {Value = TimeSpan.MinValue}; - var fetched = session.Query.All().Single(e => e.Value==TimeSpan.MinValue); + var fetched = session.Query.All().Single(e => e.Value == TimeSpan.MinValue); Assert.That(fetched, Is.EqualTo(created)); - created = new EntityWithTimeSpan {Value = TimeSpan.MaxValue}; - fetched = session.Query.All().Single(e => e.Value==TimeSpan.MaxValue); + } + } + + [Test] + public void MaxTest() + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + var created = new EntityWithTimeSpan { Value = TimeSpan.MaxValue }; + var fetched = session.Query.All().Single(e => e.Value == TimeSpan.MaxValue); Assert.That(fetched, Is.EqualTo(created)); - tx.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0471_LikeOperatorSupport.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0471_LikeOperatorSupport.cs index 427b8fff1f..49f0619b96 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0471_LikeOperatorSupport.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0471_LikeOperatorSupport.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2013 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2013-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2013.08.12 @@ -79,9 +79,9 @@ where a.FirstName.Like("E!%ric", '!') } [Test] - public void AllInOneTest() + public void AllInOneForSqlServerTest() { - Require.ProviderIsNot(StorageProvider.Firebird);// specified escape character can't be used in firebird + Require.ProviderIs(StorageProvider.SqlServer); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var firstQuery = from a in session.Query.All() @@ -92,14 +92,14 @@ where a.LastName.Like("K!%![m%f_", '!') } [Test] - public void AllInOneForFirebirdTest() + public void AllInOneTest() { - Require.ProviderIs(StorageProvider.Firebird); + Require.ProviderIsNot(StorageProvider.SqlServer); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var firstQuery = from a in session.Query.All() - where a.LastName.Like("K$%[m%f_", '$') - select a; + where a.LastName.Like("K$%[m%f_", '$') + select a; Assert.That(firstQuery.First().LastName, Is.EqualTo("K%[maroff")); } } @@ -114,15 +114,14 @@ protected override DomainConfiguration BuildConfiguration() protected override void PopulateData() { using (var session = Domain.OpenSession()) - using (var transaction = session.OpenTransaction()) - { - new Customer { FirstName = "Alexey", LastName = "Kulakov" }; - new Customer { FirstName = "Ulexey", LastName = "Kerzhakov" }; - new Customer { FirstName = "Klexey", LastName = "Komarov" }; - new Customer { FirstName = "Klexey", LastName = "K%[maroff" }; - new Customer { FirstName = "Martha", LastName = "$mith" }; - new Customer { FirstName = "E%ric", LastName = "Cartman" }; - new Customer { FirstName = "Kyle", LastName = "Broflovski" }; + using (var transaction = session.OpenTransaction()) { + _ = new Customer { FirstName = "Alexey", LastName = "Kulakov" }; + _ = new Customer { FirstName = "Ulexey", LastName = "Kerzhakov" }; + _ = new Customer { FirstName = "Klexey", LastName = "Komarov" }; + _ = new Customer { FirstName = "Klexey", LastName = "K%[maroff" }; + _ = new Customer { FirstName = "Martha", LastName = "$mith" }; + _ = new Customer { FirstName = "E%ric", LastName = "Cartman" }; + _ = new Customer { FirstName = "Kyle", LastName = "Broflovski" }; transaction.Complete(); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs index a192454c9f..bd6ddbc37a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0627_PocoClassPropertyRenitialization.cs @@ -2112,13 +2112,13 @@ public void UnionOfPocos05Test() private void RequireProviderDeniesOrderByNull() { Require.ProviderIsNot(StorageProvider.Sqlite | StorageProvider.PostgreSql | - StorageProvider.MySql | StorageProvider.Firebird); + StorageProvider.MySql | StorageProvider.Firebird | StorageProvider.Oracle); } private void RequireProviderAllowsOrderByNull() { Require.ProviderIs(StorageProvider.Sqlite | StorageProvider.PostgreSql | - StorageProvider.MySql | StorageProvider.Firebird); + StorageProvider.MySql | StorageProvider.Firebird | StorageProvider.Oracle); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0643_OracleDateTimeOffsetExtractionBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0643_OracleDateTimeOffsetExtractionBug.cs index 737dae4580..853403c9f5 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0643_OracleDateTimeOffsetExtractionBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0643_OracleDateTimeOffsetExtractionBug.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2016 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2016-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Kulakov // Created: 2016.04.29 @@ -53,19 +53,21 @@ public void MainTest() protected override void CheckRequirements() { Require.ProviderIs(StorageProvider.Oracle); - Require.AllFeaturesSupported(ProviderFeatures.DateTimeOffset); } protected override void PopulateData() { + var baseDateTime = new DateTime(2020, 08, 18, 19, 20, 21, 22); + var baseDateTimeOffset = new DateTimeOffset(baseDateTime, new TimeSpan(5, 0, 0)); + dates = new DateTime[5]; dateTimeOffsets = new DateTimeOffset[5]; using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { for (int i = 0; i < 5; i++) { - new TestEntity { - DateTimeField = dates[i] = DateTime.Now.AddHours(i), - DateTimeOffsetField = dateTimeOffsets[i] = DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(i)) + _ = new TestEntity { + DateTimeField = dates[i] = baseDateTime.AddHours(i), + DateTimeOffsetField = dateTimeOffsets[i] = baseDateTimeOffset.ToOffset(TimeSpan.FromHours(i)) }; } transaction.Complete(); From 45360669e980f9b7211f2379b975328d76434bdd Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 7 May 2021 07:58:10 +0500 Subject: [PATCH 65/71] Revert some requirements Native type for storing TimeSpans can be promoted to better precision later on, so let the problem be uncovered --- Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs | 2 +- .../Issues/IssueJira0449_TimeSpanMinMaxValue.cs | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs index d89cf2b601..bd68a0ca5d 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0818_NanosecondTrancation.cs @@ -42,7 +42,7 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - Require.ProviderIsNot(StorageProvider.PostgreSql | StorageProvider.Oracle); // PostgreSql and Oracle store intervals with microseconds only + Require.ProviderIsNot(StorageProvider.PostgreSql); // PostgreSql stores intervals with microseconds only long ticks = 123456789; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs index e016ebe473..b275ae918b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0449_TimeSpanMinMaxValue.cs @@ -38,8 +38,6 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MinTest() { - Require.ProviderIsNot(StorageProvider.Oracle, "Oracle has no resolution for TimeSpan.MinValue"); - using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { var created = new EntityWithTimeSpan {Value = TimeSpan.MinValue}; From 632d0869f298d2beeff661a1e7688df7d635eb98 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Fri, 7 May 2021 09:42:13 +0500 Subject: [PATCH 66/71] Fix TimeSpan negation compiler for Oracle --- .../MemberCompilers/TimeSpanCompilers.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/TimeSpanCompilers.cs b/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/TimeSpanCompilers.cs index dfa337909f..c54f5a3188 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/TimeSpanCompilers.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/Expressions/MemberCompilers/TimeSpanCompilers.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2021 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 // Created: 2009.02.24 @@ -15,13 +15,10 @@ namespace Xtensive.Orm.Providers [CompilerContainer(typeof(SqlExpression))] internal static class TimeSpanCompilers { - private static readonly long TicksPerMillisecond = TimeSpan.FromMilliseconds(1).Ticks; - private static readonly double MillisecondsPerDay = TimeSpan.FromDays(1).TotalMilliseconds; private static readonly double MillisecondsPerHour = TimeSpan.FromHours(1).TotalMilliseconds; private static readonly double MillisecondsPerMinute = TimeSpan.FromMinutes(1).TotalMilliseconds; private static readonly double MillisecondsPerSecond = TimeSpan.FromSeconds(1).TotalMilliseconds; - private static readonly double MillisecondsPerTick = TimeSpan.FromTicks(1).TotalMilliseconds; private const int NanosecondsPerTick = 100; private const int NanosecondsPerMillisecond = 1000000; @@ -272,6 +269,11 @@ public static SqlExpression TimeSpanOperatorUnaryPlus( public static SqlExpression TimeSpanOperatorUnaryNegation( [Type(typeof(TimeSpan))] SqlExpression t) { + var context = ExpressionTranslationContext.Current; + var isOracle = context.ProviderInfo.ProviderName.Equals(WellKnown.Provider.Oracle, StringComparison.Ordinal); + if (isOracle) { + return (-1 * t); + } return -t; } From 01b288c5d0c0b422fb21a83969df6fbb34ec3bdb Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Tue, 11 May 2021 16:21:09 +0500 Subject: [PATCH 67/71] Oracle is included to spectial check of test results + distinct by Blogs avoided --- Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs b/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs index 3fecdb2623..6d15682c74 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/DistinctTest.cs @@ -20,7 +20,7 @@ public class DistinctTest : ChinookDOModelTest [Test] public void BlobTest() { - Require.ProviderIsNot(StorageProvider.SqlServerCe); + Require.ProviderIsNot(StorageProvider.SqlServerCe | StorageProvider.Oracle); var result = Session.Query.All().Select(c => c.Bytes).Distinct(); var list = result.ToList(); } @@ -38,7 +38,7 @@ public void OrderBy2Test() .Select(c => c.Address.City) .Distinct() .OrderBy(c => c); - if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird | StorageProvider.Sqlite)) { + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird | StorageProvider.Sqlite | StorageProvider.Oracle)) { var storage = result.AsEnumerable().Where(c => !c.StartsWith('S')); var local = expected.Where(c => !c.StartsWith('S')); Assert.IsTrue(local.SequenceEqual(storage)); @@ -108,7 +108,7 @@ public void DistinctOrderByTest() .Distinct() .OrderBy(c => c); - if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird | StorageProvider.Sqlite)) { + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird | StorageProvider.Sqlite | StorageProvider.Oracle)) { var storage = result.AsEnumerable().Where(c => !c.StartsWith('S')); var local = expected.Where(c => !c.StartsWith('S')); Assert.IsTrue(local.SequenceEqual(storage)); From f4e49cce34e31c8a209164f4be7546fba4dec2ed Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 12 May 2021 18:19:14 +0500 Subject: [PATCH 68/71] Oracle is excluded from test storages for test + domain correct domain disposal in case of exception and use .ToArray(count) --- .../Issues/IssueJira0778_PrefetchStackOverflow.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs index 06a7a90352..e2a649aeed 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0778_PrefetchStackOverflow.cs @@ -28,6 +28,8 @@ private class TestDataInvalidException : Exception private bool isSchemaRecreated = false; + protected override void CheckRequirements() => Require.ProviderIsNot(StorageProvider.Oracle); + protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); @@ -39,20 +41,23 @@ protected override Domain BuildDomain(DomainConfiguration configuration) { var firstTryConfig = configuration.Clone(); firstTryConfig.UpgradeMode = DomainUpgradeMode.Validate; + Domain domain = null; try { //try to avoid long population - var domain = base.BuildDomain(firstTryConfig); + domain = base.BuildDomain(firstTryConfig); ValidateTestData(domain); return domain; } catch (SchemaSynchronizationException exception) { //schemas differ isSchemaRecreated = true; + domain.DisposeSafely(); } catch (TestDataInvalidException) { // schemas are the same but data in not ok // create so override existing schema and publish correct data isSchemaRecreated = true; + domain.DisposeSafely(); } var secondTryConfig = configuration.Clone(); secondTryConfig.UpgradeMode = DomainUpgradeMode.Recreate; @@ -352,10 +357,11 @@ private static void PopulateContactsForEmployees(Domain domain) { using (var session = domain.OpenSession()) using (var tx = session.OpenTransaction()) { - foreach (var employee in session.Query.All()) { + foreach (var employee in session.Query.All().ToArray(45)) { _ = new Contact(session, employee, ContactType.Email, ContactGenerator.GetEmail()) { Active = true }; _ = new Contact(session, employee, ContactType.Fax, ContactGenerator.GetPhone()) { Active = true }; _ = new Contact(session, employee, ContactType.Phone, ContactGenerator.GetPhone()) { Active= true }; + session.SaveChanges(); } tx.Complete(); } @@ -366,7 +372,7 @@ public static void PopulateRecipients(Domain domain) var random = new Random(); using (var session = domain.OpenSession()) using (var tx = session.OpenTransaction()) { - var customers = session.Query.All().ToArray(); + var customers = session.Query.All().ToArray(CustomerCount); foreach (var customer in customers) { var contactsToChoose = customer.Contacts.ToArray(); _ = new Recipient(session, new Audience(session)) { From b4d8340e47a2fabb19f8be5fc67054986d39146f Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Wed, 12 May 2021 18:21:02 +0500 Subject: [PATCH 69/71] Reverts commit dc569c2 --- .../Sql.Drivers.Oracle/v11/Translator.cs | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs index e9b02b83d9..9bf7729c31 100644 --- a/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs +++ b/Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v11/Translator.cs @@ -13,26 +13,6 @@ namespace Xtensive.Sql.Drivers.Oracle.v11 { internal class Translator : v10.Translator { - //so called INITRANS value - protected const int TableTransactionalParallelismLevel = 7; - protected const int IndexTransactionalParallelismLevel = 7; - - public override string Translate(SqlCompilerContext context, SqlCreateTable node, CreateTableSection section) - { - if (section == CreateTableSection.TableElementsExit) - return $") INITRANS {TableTransactionalParallelismLevel} "; - return base.Translate(context, node, section); - } - - public override string Translate(SqlCompilerContext context, SqlCreateIndex node, CreateIndexSection section) - { - if (section == CreateIndexSection.ColumnsExit) - return $") INITRANS {IndexTransactionalParallelismLevel}"; - //CreateIndexSection.ColumnsExit: - //return ")" - return base.Translate(context, node, section); - } - public override string Translate(SqlCompilerContext context, SqlOrder node, NodeSection section) { if (section == NodeSection.Exit) { From b0ee53dc797d215c7228f27d865bc024dc9a59ce Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 13 May 2021 12:14:13 +0500 Subject: [PATCH 70/71] Improve changelog --- ChangeLog/6.0.6_dev.txt | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/ChangeLog/6.0.6_dev.txt b/ChangeLog/6.0.6_dev.txt index f085d25f7d..8aafa71b22 100644 --- a/ChangeLog/6.0.6_dev.txt +++ b/ChangeLog/6.0.6_dev.txt @@ -1,8 +1,24 @@ [main] Fixed possible cases of broken serialization due to comparers [main] Fixed rare cases of insert wrong data into some table columns for SingleTable hierarchies -[sqlserver] Fixed incorrect DateTimeOffset.Date part extraction -[sqlserver] Improved translation of DateTimeOffset.LocalDateTime and DateTimeOffset.TimeOfDay parts extraction +[main] Exception message about unsupported by storage type became more informative +[firebird] Another error code that means unique contraint violation is treated correctly +[firebird] Improved Float and Double constants formatting +[firebird] Improved work with DateTime query parameters +[firebird] Fixed column's default value extraction +[mysql] Another error code that means unique contraint violation is treated correctly +[mysql] Fixed DateTime.DayOfWeek translation +[oracle] Changed NULLs ordering settings. Now order is the same as in .NET +[oracle] Improved resolution of TimeSpan literal values on translation +[oracle] Starting from v11 schema names don't have to be in upper-case as storage allowes names in any case +[oracle] Improved translation of Math.Ceiling(), Math.Truncate() and Math.Floor() +[oracle] Fixed byte array fields comparison translation e.g. in Where statements +[oracle] Improved translation of DateTimeOffset's LocalDateTime, ToLocalTime() and ToUniversalTime() members [postgresql] Improved performance of First(), FirstOrDefault() being subqueries -[postgresql] Improved translation of Math.Ceiling(), Math.Truncate() and Math.Floor() +[postgresql] Improved translation of Math.Ceiling(), Math.Truncate() and Math.Floor() methods +[postgresql] Skip Commit/Rollback operations on already completed transaction to prevent exception overlaping +[sqlite] Fixed some foreign key extraction issues +[sqlite] Improved work with DateTime query parameters +[sqlserver] Fixed incorrect DateTimeOffset.Date part extraction +[sqlserver] Improved translation of DateTimeOffset' LocalDateTime and TimeOfDay members [reprocessing] ExecuteActionStrategy.Execute doesn't get external session though Session.Current at all -[reprocessing] Introduced DomainExtension.WithSession and IExecuteConfiguration WithSession methods to pass external session \ No newline at end of file +[reprocessing] Introduced DomainExtension.WithSession() and IExecuteConfiguration.WithSession() methods to pass external session \ No newline at end of file From a80dc770fb70cf8d12c2db87f1bb690ed1993af9 Mon Sep 17 00:00:00 2001 From: Alexey Kulakov Date: Thu, 13 May 2021 14:59:19 +0500 Subject: [PATCH 71/71] Improve changelog --- ChangeLog/6.0.6_dev.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ChangeLog/6.0.6_dev.txt b/ChangeLog/6.0.6_dev.txt index 8aafa71b22..60312fd551 100644 --- a/ChangeLog/6.0.6_dev.txt +++ b/ChangeLog/6.0.6_dev.txt @@ -2,9 +2,9 @@ [main] Fixed rare cases of insert wrong data into some table columns for SingleTable hierarchies [main] Exception message about unsupported by storage type became more informative [firebird] Another error code that means unique contraint violation is treated correctly -[firebird] Improved Float and Double constants formatting +[firebird] Improved formatting for Float and Double constants within queries [firebird] Improved work with DateTime query parameters -[firebird] Fixed column's default value extraction +[firebird] Fixed columns' default value extraction [mysql] Another error code that means unique contraint violation is treated correctly [mysql] Fixed DateTime.DayOfWeek translation [oracle] Changed NULLs ordering settings. Now order is the same as in .NET @@ -15,10 +15,10 @@ [oracle] Improved translation of DateTimeOffset's LocalDateTime, ToLocalTime() and ToUniversalTime() members [postgresql] Improved performance of First(), FirstOrDefault() being subqueries [postgresql] Improved translation of Math.Ceiling(), Math.Truncate() and Math.Floor() methods -[postgresql] Skip Commit/Rollback operations on already completed transaction to prevent exception overlaping +[postgresql] Skip Commit/Rollback operations for already completed transaction to prevent exception overlaping [sqlite] Fixed some foreign key extraction issues [sqlite] Improved work with DateTime query parameters [sqlserver] Fixed incorrect DateTimeOffset.Date part extraction -[sqlserver] Improved translation of DateTimeOffset' LocalDateTime and TimeOfDay members +[sqlserver] Improved translation of DateTimeOffset's LocalDateTime and TimeOfDay members [reprocessing] ExecuteActionStrategy.Execute doesn't get external session though Session.Current at all [reprocessing] Introduced DomainExtension.WithSession() and IExecuteConfiguration.WithSession() methods to pass external session \ No newline at end of file