From 0d1a4b72a87fdc832d6825ffd3aa1f1914b96a5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Tue, 13 Mar 2018 14:04:41 +0100 Subject: [PATCH 1/2] Clean filters tests * Add proper SetUp and Teardown * Add missing using () --- .../Async/FilterTest/DynamicFilterTest.cs | 1102 +++++++++-------- .../FilterTest/DynamicFilterTest.cs | 941 +++++++------- 2 files changed, 1011 insertions(+), 1032 deletions(-) diff --git a/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs b/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs index 8814d227e94..59133287cce 100644 --- a/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs +++ b/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs @@ -11,13 +11,10 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using log4net; using NHibernate.Cache; using NHibernate.Cache.Entry; using NHibernate.Criterion; -using NHibernate.Engine; -using NHibernate.Persister.Collection; using NHibernate.Transform; using NUnit.Framework; @@ -28,118 +25,119 @@ namespace NHibernate.Test.FilterTest [TestFixture] public class DynamicFilterTestAsync : TestCase { - private ILog log = LogManager.GetLogger(typeof(DynamicFilterTestAsync)); + private static readonly ILog log = LogManager.GetLogger(typeof(DynamicFilterTestAsync)); + private TestData testData; - [Test] - public async Task SecondLevelCachedCollectionsFilteringAsync() + protected override void OnSetUp() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); + testData = new TestData(this); + testData.Prepare(); + } - ISession session = OpenSession(); + protected override void OnTearDown() + { + testData.Release(); + } - // Force a collection into the second level cache, with its non-filtered elements - Salesperson sp = (Salesperson) await (session.LoadAsync(typeof(Salesperson), testData.steveId)); - await (NHibernateUtil.InitializeAsync(sp.Orders)); - ICollectionPersister persister = ((ISessionFactoryImplementor) Sfi) + [Test] + public async Task SecondLevelCachedCollectionsFilteringAsync() + { + var persister = Sfi .GetCollectionPersister(typeof(Salesperson).FullName + ".Orders"); - Assert.IsTrue(persister.HasCache, "No cache for collection"); - CacheKey cacheKey = - new CacheKey(testData.steveId, persister.KeyType, persister.Role, (ISessionFactoryImplementor) Sfi); - CollectionCacheEntry cachedData = (CollectionCacheEntry)await (persister.Cache.Cache.GetAsync(cacheKey, CancellationToken.None)); - Assert.IsNotNull(cachedData, "collection was not in cache"); - - session.Close(); - - session = OpenSession(); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - sp = (Salesperson) await (session.CreateQuery("from Salesperson as s where s.id = :id") - .SetInt64("id", testData.steveId) - .UniqueResultAsync()); - Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); + var cacheKey = + new CacheKey(testData.steveId, persister.KeyType, persister.Role, Sfi); + CollectionCacheEntry cachedData; - CollectionCacheEntry cachedData2 = (CollectionCacheEntry)await (persister.Cache.Cache.GetAsync(cacheKey, CancellationToken.None)); - Assert.IsNotNull(cachedData2, "collection no longer in cache!"); - Assert.AreSame(cachedData, cachedData2, "Different cache values!"); - - session.Close(); + using (var session = OpenSession()) + { + // Force a collection into the second level cache, with its non-filtered elements + var sp = (Salesperson) await (session.LoadAsync(typeof(Salesperson), testData.steveId)); + await (NHibernateUtil.InitializeAsync(sp.Orders)); + Assert.IsTrue(persister.HasCache, "No cache for collection"); + cachedData = (CollectionCacheEntry) await (persister.Cache.Cache.GetAsync(cacheKey, CancellationToken.None)); + Assert.IsNotNull(cachedData, "collection was not in cache"); + } - session = OpenSession(); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - sp = (Salesperson) await (session.LoadAsync(typeof(Salesperson), testData.steveId)); - Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); + using (var session = OpenSession()) + { + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); + var sp = (Salesperson) await (session.CreateQuery("from Salesperson as s where s.id = :id") + .SetInt64("id", testData.steveId) + .UniqueResultAsync()); + Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); + + CollectionCacheEntry cachedData2 = (CollectionCacheEntry) await (persister.Cache.Cache.GetAsync(cacheKey, CancellationToken.None)); + Assert.IsNotNull(cachedData2, "collection no longer in cache!"); + Assert.AreSame(cachedData, cachedData2, "Different cache values!"); + } - session.Close(); + using (var session = OpenSession()) + { + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); + var sp = (Salesperson) await (session.LoadAsync(typeof(Salesperson), testData.steveId)); + Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); + } // Finally, make sure that the original cached version did not get over-written - session = OpenSession(); - sp = (Salesperson) await (session.LoadAsync(typeof(Salesperson), testData.steveId)); - Assert.AreEqual(2, sp.Orders.Count, "Actual cached version got over-written"); - - session.Close(); - await (testData.ReleaseAsync()); + using (var session = OpenSession()) + { + var sp = (Salesperson) await (session.LoadAsync(typeof(Salesperson), testData.steveId)); + Assert.AreEqual(2, sp.Orders.Count, "Actual cached version got over-written"); + } } [Test] public async Task CombinedClassAndCollectionFiltersEnabledAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("regionlist").SetParameterList("regions", new string[] {"LA", "APAC"}); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - - // test retreival through hql with the collection as non-eager - IList salespersons = await (session.CreateQuery("select s from Salesperson as s").ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - Salesperson sp = (Salesperson) salespersons[0]; - Assert.AreEqual(1, sp.Orders.Count, "Incorrect order count"); - - session.Clear(); - - // test retreival through hql with the collection join fetched - salespersons = await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - sp = (Salesperson) salespersons[0]; - Assert.AreEqual(sp.Orders.Count, 1, "Incorrect order count"); - - session.Close(); - await (testData.ReleaseAsync()); + using (var session = OpenSession()) + { + session.EnableFilter("regionlist").SetParameterList("regions", new[] { "LA", "APAC" }); + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); + + // test retreival through hql with the collection as non-eager + IList salespersons = await (session.CreateQuery("select s from Salesperson as s").ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + Salesperson sp = (Salesperson) salespersons[0]; + Assert.AreEqual(1, sp.Orders.Count, "Incorrect order count"); + + session.Clear(); + + // test retreival through hql with the collection join fetched + salespersons = await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + sp = (Salesperson) salespersons[0]; + Assert.AreEqual(sp.Orders.Count, 1, "Incorrect order count"); + } } [Test] public async Task FiltersWithQueryCacheAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("regionlist").SetParameterList("regions", new string[] {"LA", "APAC"}); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - - // test retreival through hql with the collection as non-eager - IList salespersons = await (session.CreateQuery("select s from Salesperson as s").SetCacheable(true).ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + using (var session = OpenSession()) + { + session.EnableFilter("regionlist").SetParameterList("regions", new[] { "LA", "APAC" }); + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - // Try a second time, to make use of query cache - salespersons = await (session.CreateQuery("select s from Salesperson as s").SetCacheable(true).ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + // test retreival through hql with the collection as non-eager + IList salespersons = await (session.CreateQuery("select s from Salesperson as s").SetCacheable(true).ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - session.Clear(); + // Try a second time, to make use of query cache + salespersons = await (session.CreateQuery("select s from Salesperson as s").SetCacheable(true).ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - // test retreival through hql with the collection join fetched - salespersons = - await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + session.Clear(); - // A second time, to make use of query cache - salespersons = - await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + // test retreival through hql with the collection join fetched + salespersons = + await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - session.Close(); - await (testData.ReleaseAsync()); + // A second time, to make use of query cache + salespersons = + await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + } } [Test] @@ -149,27 +147,23 @@ public async Task HqlFiltersAsync() // HQL test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting HQL filter tests"); - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("region").SetParameter("region", "APAC"); - - session.EnableFilter("effectiveDate") - .SetParameter("asOfDate", testData.lastMonth); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); - log.Info("HQL against Salesperson..."); - IList results = await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").ListAsync()); - Assert.IsTrue(results.Count == 1, "Incorrect filtered HQL result count [" + results.Count + "]"); - Salesperson result = (Salesperson) results[0]; - Assert.IsTrue(result.Orders.Count == 1, "Incorrect collectionfilter count"); + session.EnableFilter("effectiveDate") + .SetParameter("asOfDate", testData.lastMonth); - log.Info("HQL against Product..."); - results = await (session.CreateQuery("from Product as p where p.StockNumber = ?").SetInt32(0, 124).ListAsync()); - Assert.IsTrue(results.Count == 1); + log.Info("HQL against Salesperson..."); + IList results = await (session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").ListAsync()); + Assert.IsTrue(results.Count == 1, "Incorrect filtered HQL result count [" + results.Count + "]"); + Salesperson result = (Salesperson) results[0]; + Assert.IsTrue(result.Orders.Count == 1, "Incorrect collectionfilter count"); - session.Close(); - await (testData.ReleaseAsync()); + log.Info("HQL against Product..."); + results = await (session.CreateQuery("from Product as p where p.StockNumber = ?").SetInt32(0, 124).ListAsync()); + Assert.IsTrue(results.Count == 1); + } } [Test] @@ -179,63 +173,55 @@ public async Task CriteriaQueryFiltersAsync() // Criteria-query test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting Criteria-query filter tests"); - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("region").SetParameter("region", "APAC"); - - session.EnableFilter("fulfilledOrders") - .SetParameter("asOfDate", testData.lastMonth); - - session.EnableFilter("effectiveDate") - .SetParameter("asOfDate", testData.lastMonth); - - log.Info("Criteria query against Salesperson..."); - IList salespersons = await (session.CreateCriteria(typeof(Salesperson)) - .SetFetchMode("orders", FetchMode.Join) - .ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - Assert.AreEqual(1, ((Salesperson) salespersons[0]).Orders.Count, "Incorrect order count"); - log.Info("Criteria query against Product..."); - IList products = await (session.CreateCriteria(typeof(Product)) - .Add(Expression.Eq("StockNumber", 124)) - .ListAsync()); - Assert.AreEqual(1, products.Count, "Incorrect product count"); - - session.Close(); - await (testData.ReleaseAsync()); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); + + session.EnableFilter("fulfilledOrders") + .SetParameter("asOfDate", testData.lastMonth); + + session.EnableFilter("effectiveDate") + .SetParameter("asOfDate", testData.lastMonth); + + log.Info("Criteria query against Salesperson..."); + IList salespersons = await (session.CreateCriteria(typeof(Salesperson)) + .SetFetchMode("orders", FetchMode.Join) + .ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + Assert.AreEqual(1, ((Salesperson) salespersons[0]).Orders.Count, "Incorrect order count"); + + log.Info("Criteria query against Product..."); + IList products = await (session.CreateCriteria(typeof(Product)) + .Add(Expression.Eq("StockNumber", 124)) + .ListAsync()); + Assert.AreEqual(1, products.Count, "Incorrect product count"); + } } [Test] public async Task CriteriaControlAsync() { - using (var testData = new TestData(this)) - { - await (testData.PrepareAsync()); - - // the subquery... - var subquery = DetachedCriteria - .For() - .SetProjection(Property.ForName("Name")); + // the subquery... + var subquery = DetachedCriteria + .For() + .SetProjection(Property.ForName("Name")); - using (var session = OpenSession()) - using (var transaction = session.BeginTransaction()) - { - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth.Date); - session.EnableFilter("regionlist").SetParameter("regions", "APAC"); + using (var session = OpenSession()) + using (var transaction = session.BeginTransaction()) + { + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth.Date); + session.EnableFilter("regionlist").SetParameter("regions", "APAC"); - var result = await (session - .CreateCriteria() - .Add(Subqueries.In("steve", subquery)) - .ListAsync()); + var result = await (session + .CreateCriteria() + .Add(Subqueries.In("steve", subquery)) + .ListAsync()); - Assert.That(result.Count, Is.EqualTo(1)); + Assert.That(result.Count, Is.EqualTo(1)); - await (transaction.CommitAsync()); - } + await (transaction.CommitAsync()); } } @@ -246,85 +232,81 @@ public async Task CriteriaSubqueryWithFiltersAsync() // Criteria-subquery test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting Criteria-subquery filter tests"); - using (var testData = new TestData(this)) - { - await (testData.PrepareAsync()); - using (var session = OpenSession()) - { - session.EnableFilter("region").SetParameter("region", "APAC"); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); - log.Info("Criteria query against Department with a subquery on Salesperson in the APAC reqion..."); - var salespersonSubquery = DetachedCriteria.For() - .Add(Restrictions.Eq("Name", "steve")) - .SetProjection(Property.ForName("Department")); + log.Info("Criteria query against Department with a subquery on Salesperson in the APAC reqion..."); + var salespersonSubquery = DetachedCriteria.For() + .Add(Restrictions.Eq("Name", "steve")) + .SetProjection(Property.ForName("Department")); - var departmentsQuery = session.CreateCriteria(). - Add(Subqueries.PropertyIn("Id", salespersonSubquery)); - var departments = await (departmentsQuery.ListAsync()); + var departmentsQuery = session.CreateCriteria(). + Add(Subqueries.PropertyIn("Id", salespersonSubquery)); + var departments = await (departmentsQuery.ListAsync()); - Assert.That(departments.Count, Is.EqualTo(1), "Incorrect department count"); + Assert.That(departments.Count, Is.EqualTo(1), "Incorrect department count"); - log.Info("Criteria query against Department with a subquery on Salesperson in the FooBar reqion..."); + log.Info("Criteria query against Department with a subquery on Salesperson in the FooBar reqion..."); - session.EnableFilter("region").SetParameter("region", "Foobar"); - departments = await (departmentsQuery.ListAsync()); + session.EnableFilter("region").SetParameter("region", "Foobar"); + departments = await (departmentsQuery.ListAsync()); - Assert.That(departments.Count, Is.EqualTo(0), "Incorrect department count"); + Assert.That(departments.Count, Is.EqualTo(0), "Incorrect department count"); - log.Info("Criteria query against Order with a subquery for line items with a subquery on product and sold by a given sales person..."); - session.EnableFilter("region").SetParameter("region", "APAC"); + log.Info("Criteria query against Order with a subquery for line items with a subquery on product and sold by a given sales person..."); + session.EnableFilter("region").SetParameter("region", "APAC"); - var lineItemSubquery = DetachedCriteria.For() - .Add(Restrictions.Ge("Quantity", 1L)) - .CreateCriteria("Product") - .Add(Restrictions.Eq("Name", "Acme Hair Gel")) - .SetProjection(Property.ForName("Id")); + var lineItemSubquery = DetachedCriteria.For() + .Add(Restrictions.Ge("Quantity", 1L)) + .CreateCriteria("Product") + .Add(Restrictions.Eq("Name", "Acme Hair Gel")) + .SetProjection(Property.ForName("Id")); - var orders = await (session.CreateCriteria() - .Add(Subqueries.Exists(lineItemSubquery)) - .Add(Restrictions.Eq("Buyer", "gavin")) - .ListAsync()); + var orders = await (session.CreateCriteria() + .Add(Subqueries.Exists(lineItemSubquery)) + .Add(Restrictions.Eq("Buyer", "gavin")) + .ListAsync()); - Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); + Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); - log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); - session.EnableFilter("region").SetParameter("region", "APAC"); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.lastMonth.Date); + log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); + session.EnableFilter("region").SetParameter("region", "APAC"); + session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.lastMonth.Date); - var productSubquery = DetachedCriteria.For() - . - Add(Restrictions.Eq("Name", "Acme Hair Gel")) - .SetProjection(Property.ForName("id")); + var productSubquery = DetachedCriteria.For() + . + Add(Restrictions.Eq("Name", "Acme Hair Gel")) + .SetProjection(Property.ForName("id")); - lineItemSubquery = DetachedCriteria.For() - .Add(Restrictions.Ge("Quantity", 1L)) - .CreateCriteria("Product") - .Add(Subqueries.PropertyIn("Id", productSubquery)) - .SetProjection(Property.ForName("Id")); + lineItemSubquery = DetachedCriteria.For() + .Add(Restrictions.Ge("Quantity", 1L)) + .CreateCriteria("Product") + .Add(Subqueries.PropertyIn("Id", productSubquery)) + .SetProjection(Property.ForName("Id")); - orders = await (session - .CreateCriteria() - .Add(Subqueries.Exists(lineItemSubquery)) - .Add(Restrictions.Eq("Buyer", "gavin")) - .ListAsync()); + orders = await (session + .CreateCriteria() + .Add(Subqueries.Exists(lineItemSubquery)) + .Add(Restrictions.Eq("Buyer", "gavin")) + .ListAsync()); - Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); + Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); - log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); - session.EnableFilter("region").SetParameter("region", "APAC"); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.fourMonthsAgo.Date); + log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); + session.EnableFilter("region").SetParameter("region", "APAC"); + session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.fourMonthsAgo.Date); - orders = await (session.CreateCriteria() - .Add(Subqueries.Exists(lineItemSubquery)) - .Add(Restrictions.Eq("Buyer", "gavin")) - .ListAsync()); + orders = await (session.CreateCriteria() + .Add(Subqueries.Exists(lineItemSubquery)) + .Add(Restrictions.Eq("Buyer", "gavin")) + .ListAsync()); - Assert.That(orders.Count, Is.EqualTo(0), "Incorrect orders count"); + Assert.That(orders.Count, Is.EqualTo(0), "Incorrect orders count"); - session.Close(); - } + session.Close(); } } @@ -336,19 +318,15 @@ public async Task GetFiltersAsync() // Get() test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting get() filter tests (eager assoc. fetching)."); - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("region").SetParameter("region", "APAC"); - - log.Info("Performing get()..."); - Salesperson salesperson = (Salesperson) await (session.GetAsync(typeof(Salesperson), testData.steveId)); - Assert.IsNotNull(salesperson); - Assert.AreEqual(1, salesperson.Orders.Count, "Incorrect order count"); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); - session.Close(); - await (testData.ReleaseAsync()); + log.Info("Performing get()..."); + Salesperson salesperson = (Salesperson) await (session.GetAsync(typeof(Salesperson), testData.steveId)); + Assert.IsNotNull(salesperson); + Assert.AreEqual(1, salesperson.Orders.Count, "Incorrect order count"); + } } [Test] @@ -358,20 +336,16 @@ public async Task OneToManyFiltersAsync() // one-to-many loading tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting one-to-many collection loader filter tests."); - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("seniorSalespersons") - .SetParameter("asOfDate", testData.lastMonth); - - log.Info("Performing Load of Department..."); - Department department = (Department) await (session.LoadAsync(typeof(Department), testData.deptId)); - ISet salespersons = department.Salespersons; - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + using (var session = OpenSession()) + { + session.EnableFilter("seniorSalespersons") + .SetParameter("asOfDate", testData.lastMonth); - session.Close(); - await (testData.ReleaseAsync()); + log.Info("Performing Load of Department..."); + Department department = (Department) await (session.LoadAsync(typeof(Department), testData.deptId)); + ISet salespersons = department.Salespersons; + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + } } [Test] @@ -381,246 +355,215 @@ public async Task InStyleFilterParameterAsync() // one-to-many loading tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting one-to-many collection loader filter tests."); - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("regionlist") - .SetParameterList("regions", new string[] {"LA", "APAC"}); - - log.Debug("Performing query of Salespersons"); - IList salespersons = await (session.CreateQuery("from Salesperson").ListAsync()); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + using (var session = OpenSession()) + { + session.EnableFilter("regionlist") + .SetParameterList("regions", new [] { "LA", "APAC" }); - session.Close(); - await (testData.ReleaseAsync()); + log.Debug("Performing query of Salespersons"); + IList salespersons = await (session.CreateQuery("from Salesperson").ListAsync()); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + } } - [Test] + [Test] public async Task ManyToManyFilterOnCriteriaAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - - Product prod = (Product) await (session.CreateCriteria(typeof(Product)) - .SetResultTransformer(new DistinctRootEntityResultTransformer()) - .Add(Expression.Eq("id", testData.prod1Id)) - .UniqueResultAsync()); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - Assert.IsNotNull(prod); - Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter"); + Product prod = (Product) await (session.CreateCriteria(typeof(Product)) + .SetResultTransformer(new DistinctRootEntityResultTransformer()) + .Add(Expression.Eq("id", testData.prod1Id)) + .UniqueResultAsync()); - session.Close(); - await (testData.ReleaseAsync()); + Assert.IsNotNull(prod); + Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter"); + } } [Test] public async Task ManyToManyFilterOnLoadAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); + Product prod = (Product) await (session.GetAsync(typeof(Product), testData.prod1Id)); - Product prod = (Product) await (session.GetAsync(typeof(Product), testData.prod1Id)); + //long initLoadCount = sessions.Statistics.CollectionLoadCount; + //long initFetchCount = sessions.Statistics.CollectionFetchCount; - //long initLoadCount = sessions.Statistics.CollectionLoadCount; - //long initFetchCount = sessions.Statistics.CollectionFetchCount; + // should already have been initialized... + Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories)); + int size = prod.Categories.Count; + Assert.AreEqual(1, size, "Incorrect filtered collection count"); - // should already have been initialized... - Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories)); - int size = prod.Categories.Count; - Assert.AreEqual(1, size, "Incorrect filtered collection count"); + //long currLoadCount = sessions.Statistics.CollectionLoadCount; + //long currFetchCount = sessions.Statistics.CollectionFetchCount; - //long currLoadCount = sessions.Statistics.CollectionLoadCount; - //long currFetchCount = sessions.Statistics.CollectionFetchCount; + //Assert.IsTrue( + // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), + // "Load with join fetch of many-to-many did not trigger join fetch" + // ); - //Assert.IsTrue( - // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), - // "Load with join fetch of many-to-many did not trigger join fetch" - // ); + // make sure we did not get back a collection of proxies + //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; - // make sure we did not get back a collection of proxies - //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; + foreach (Category cat in prod.Categories) + { + Assert.IsTrue( + NHibernateUtil.IsInitialized(cat), + "Load with join fetch of many-to-many did not trigger *complete* join fetch"); + //Console.WriteLine(" ===> " + cat.Name); + } + //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - foreach (Category cat in prod.Categories) - { - Assert.IsTrue(NHibernateUtil.IsInitialized(cat), - "Load with join fetch of many-to-many did not trigger *complete* join fetch"); - //Console.WriteLine(" ===> " + cat.Name); + //Assert.IsTrue( + // (initEntityLoadCount == currEntityLoadCount), + // "Load with join fetch of many-to-many did not trigger *complete* join fetch" + // ); } - //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - - //Assert.IsTrue( - // (initEntityLoadCount == currEntityLoadCount), - // "Load with join fetch of many-to-many did not trigger *complete* join fetch" - // ); - - session.Close(); - await (testData.ReleaseAsync()); } [Test] public async Task ManyToManyOnCollectionLoadAfterHQLAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - - // Force the categories to not get initialized here - IList result = await (session.CreateQuery("from Product as p where p.id = :id") - .SetInt64("id", testData.prod1Id) - .ListAsync()); - Assert.IsTrue(result.Count > 0, "No products returned from HQL"); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - Product prod = (Product) result[0]; - Assert.IsNotNull(prod); - Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter on collection Load"); + // Force the categories to not get initialized here + IList result = await (session.CreateQuery("from Product as p where p.id = :id") + .SetInt64("id", testData.prod1Id) + .ListAsync()); + Assert.IsTrue(result.Count > 0, "No products returned from HQL"); - session.Close(); - await (testData.ReleaseAsync()); + Product prod = (Product) result[0]; + Assert.IsNotNull(prod); + Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter on collection Load"); + } } [Test] public async Task ManyToManyFilterOnQueryAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - - IList result = await (session.CreateQuery("from Product p inner join fetch p.Categories").ListAsync()); - Assert.IsTrue(result.Count > 0, "No products returned from HQL many-to-many filter case"); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - Product prod = (Product) result[0]; + IList result = await (session.CreateQuery("from Product p inner join fetch p.Categories").ListAsync()); + Assert.IsTrue(result.Count > 0, "No products returned from HQL many-to-many filter case"); - Assert.IsNotNull(prod); - Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter with HQL"); + Product prod = (Product) result[0]; - session.Close(); - await (testData.ReleaseAsync()); + Assert.IsNotNull(prod); + Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter with HQL"); + } } [Test] public async Task ManyToManyBaseAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); - - Product prod = (Product) await (session.GetAsync(typeof(Product), testData.prod1Id)); - - // TODO H3: Statistics - //long initLoadCount = sessions.Statistics.CollectionLoadCount; - //long initFetchCount = sessions.Statistics.CollectionFetchCount; - - // should already have been initialized... - Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories), - "Load with join fetch of many-to-many did not trigger join fetch"); - int size = prod.Categories.Count; - Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); - - //long currLoadCount = sessions.Statistics.CollectionLoadCount; - //long currFetchCount = sessions.Statistics.CollectionFetchCount; - - //Assert.IsTrue( - // ( initLoadCount == currLoadCount ) && ( initFetchCount == currFetchCount ), - // "Load with join fetch of many-to-many did not trigger join fetch" - //); - - // make sure we did not get back a collection of proxies - // TODO H3: statistics - //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; - foreach (Category cat in prod.Categories) + using (var session = OpenSession()) { - Assert.IsTrue(NHibernateUtil.IsInitialized(cat), - "Load with join fetch of many-to-many did not trigger *complete* join fetch"); - //Console.WriteLine(" ===> " + cat.Name); - } - //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - - //Assert.IsTrue( - // ( initEntityLoadCount == currEntityLoadCount ), - // "Load with join fetch of many-to-many did not trigger *complete* join fetch" - //); + Product prod = (Product) await (session.GetAsync(typeof(Product), testData.prod1Id)); + + // TODO H3: Statistics + //long initLoadCount = sessions.Statistics.CollectionLoadCount; + //long initFetchCount = sessions.Statistics.CollectionFetchCount; + + // should already have been initialized... + Assert.IsTrue( + NHibernateUtil.IsInitialized(prod.Categories), + "Load with join fetch of many-to-many did not trigger join fetch"); + int size = prod.Categories.Count; + Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); + + //long currLoadCount = sessions.Statistics.CollectionLoadCount; + //long currFetchCount = sessions.Statistics.CollectionFetchCount; + + //Assert.IsTrue( + // ( initLoadCount == currLoadCount ) && ( initFetchCount == currFetchCount ), + // "Load with join fetch of many-to-many did not trigger join fetch" + //); + + // make sure we did not get back a collection of proxies + // TODO H3: statistics + //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; + foreach (Category cat in prod.Categories) + { + Assert.IsTrue( + NHibernateUtil.IsInitialized(cat), + "Load with join fetch of many-to-many did not trigger *complete* join fetch"); + //Console.WriteLine(" ===> " + cat.Name); + } + //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - session.Close(); - await (testData.ReleaseAsync()); + //Assert.IsTrue( + // ( initEntityLoadCount == currEntityLoadCount ), + // "Load with join fetch of many-to-many did not trigger *complete* join fetch" + //); + } } [Test] public async Task ManyToManyBaseThruCriteriaAsync() { - TestData testData = new TestData(this); - await (testData.PrepareAsync()); - - ISession session = OpenSession(); + using (var session = OpenSession()) + { + IList result = await (session.CreateCriteria(typeof(Product)) + .Add(Expression.Eq("id", testData.prod1Id)) + .ListAsync()); - IList result = await (session.CreateCriteria(typeof(Product)) - .Add(Expression.Eq("id", testData.prod1Id)) - .ListAsync()); + Product prod = (Product) result[0]; - Product prod = (Product) result[0]; + //long initLoadCount = sessions.Statistics.CollectionLoadCount; + //long initFetchCount = sessions.Statistics.CollectionFetchCount; - //long initLoadCount = sessions.Statistics.CollectionLoadCount; - //long initFetchCount = sessions.Statistics.CollectionFetchCount; + // should already have been initialized... + Assert.IsTrue( + NHibernateUtil.IsInitialized(prod.Categories), + "Load with join fetch of many-to-many did not trigger join fetch"); + int size = prod.Categories.Count; + Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); - // should already have been initialized... - Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories), - "Load with join fetch of many-to-many did not trigger join fetch"); - int size = prod.Categories.Count; - Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); + //long currLoadCount = sessions.Statistics.CollectionLoadCount; + //long currFetchCount = sessions.Statistics.CollectionFetchCount; - //long currLoadCount = sessions.Statistics.CollectionLoadCount; - //long currFetchCount = sessions.Statistics.CollectionFetchCount; + //Assert.IsTrue( + // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), + // "Load with join fetch of many-to-many did not trigger join fetch" + // ); - //Assert.IsTrue( - // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), - // "Load with join fetch of many-to-many did not trigger join fetch" - // ); + // make sure we did not get back a collection of proxies + //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; + foreach (Category cat in prod.Categories) + { + Assert.IsTrue( + NHibernateUtil.IsInitialized(cat), + "Load with join fetch of many-to-many did not trigger *complete* join fetch"); + //Console.WriteLine(" ===> " + cat.Name); + } + //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - // make sure we did not get back a collection of proxies - //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; - foreach (Category cat in prod.Categories) - { - Assert.IsTrue(NHibernateUtil.IsInitialized(cat), - "Load with join fetch of many-to-many did not trigger *complete* join fetch"); - //Console.WriteLine(" ===> " + cat.Name); + //Assert.IsTrue( + // (initEntityLoadCount == currEntityLoadCount), + // "Load with join fetch of many-to-many did not trigger *complete* join fetch" + // ); } - //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - - //Assert.IsTrue( - // (initEntityLoadCount == currEntityLoadCount), - // "Load with join fetch of many-to-many did not trigger *complete* join fetch" - // ); - - session.Close(); - await (testData.ReleaseAsync()); } protected override string MappingsAssembly => "NHibernate.Test"; - protected override IList Mappings + protected override IList Mappings => new [] { - get - { - return new string[] - { - "FilterTest.defs.hbm.xml", - "FilterTest.classes.hbm.xml", - }; - } - } + "FilterTest.defs.hbm.xml", + "FilterTest.classes.hbm.xml", + }; - private class TestData:IDisposable + private class TestData { public long steveId; public long deptId; @@ -637,139 +580,236 @@ public TestData(DynamicFilterTestAsync outer) this.outer = outer; } - public IList entitiesToCleanUp = new List(); + private readonly IList entitiesToCleanUp = new List(); public async Task PrepareAsync(CancellationToken cancellationToken = default(CancellationToken)) { - ISession session = outer.OpenSession(); - ITransaction transaction = session.BeginTransaction(); - - lastMonth = DateTime.Today.AddMonths(-1); - nextMonth = DateTime.Today.AddMonths(1); - - sixMonthsAgo = DateTime.Today.AddMonths(-6); - fourMonthsAgo = DateTime.Today.AddMonths(-4); - - Department dept = new Department(); - dept.Name = ("Sales"); - - await (session.SaveAsync(dept, cancellationToken)); - deptId = dept.Id; - entitiesToCleanUp.Add(dept); - - Salesperson steve = new Salesperson(); - steve.Name = ("steve"); - steve.Region = ("APAC"); - steve.HireDate = (sixMonthsAgo); - - steve.Department = (dept); - dept.Salespersons.Add(steve); - - Salesperson max = new Salesperson(); - max.Name = ("max"); - max.Region = ("EMEA"); - max.HireDate = (nextMonth); - - max.Department = (dept); - dept.Salespersons.Add(max); - - await (session.SaveAsync(steve, cancellationToken)); - await (session.SaveAsync(max, cancellationToken)); - entitiesToCleanUp.Add(steve); - entitiesToCleanUp.Add(max); - - steveId = steve.Id; - - Category cat1 = new Category("test cat 1", lastMonth, nextMonth); - Category cat2 = new Category("test cat 2", sixMonthsAgo, fourMonthsAgo); - - Product product1 = new Product(); - product1.Name = ("Acme Hair Gel"); - product1.StockNumber = (123); - product1.EffectiveStartDate = (lastMonth); - product1.EffectiveEndDate = (nextMonth); - - product1.AddCategory(cat1); - product1.AddCategory(cat2); - - await (session.SaveAsync(product1, cancellationToken)); - entitiesToCleanUp.Add(product1); - prod1Id = product1.Id; - - Order order1 = new Order(); - order1.Buyer = "gavin"; - order1.Region = ("APAC"); - order1.PlacementDate = sixMonthsAgo; - order1.FulfillmentDate = fourMonthsAgo; - order1.Salesperson = steve; - order1.AddLineItem(product1, 500); - - await (session.SaveAsync(order1, cancellationToken)); - entitiesToCleanUp.Add(order1); - - Product product2 = new Product(); - product2.Name = ("Acme Super-Duper DTO Factory"); - product2.StockNumber = (124); - product2.EffectiveStartDate = (sixMonthsAgo); - product2.EffectiveEndDate = (DateTime.Today); - - Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); - product2.AddCategory(cat3); - - await (session.SaveAsync(product2, cancellationToken)); - entitiesToCleanUp.Add(product2); - - // An uncategorized product - Product product3 = new Product(); - product3.Name = ("Uncategorized product"); - await (session.SaveAsync(product3, cancellationToken)); - entitiesToCleanUp.Add(product3); - - Order order2 = new Order(); - order2.Buyer = "christian"; - order2.Region = ("EMEA"); - order2.PlacementDate = lastMonth; - order2.Salesperson = steve; - order2.AddLineItem(product2, -1); - - await (session.SaveAsync(order2, cancellationToken)); - entitiesToCleanUp.Add(order2); + using (var session = outer.OpenSession()) + using (var transaction = session.BeginTransaction()) + { + lastMonth = DateTime.Today.AddMonths(-1); + nextMonth = DateTime.Today.AddMonths(1); + + sixMonthsAgo = DateTime.Today.AddMonths(-6); + fourMonthsAgo = DateTime.Today.AddMonths(-4); + + Department dept = new Department(); + dept.Name = ("Sales"); + + await (session.SaveAsync(dept, cancellationToken)); + deptId = dept.Id; + entitiesToCleanUp.Add(dept); + + Salesperson steve = new Salesperson(); + steve.Name = ("steve"); + steve.Region = ("APAC"); + steve.HireDate = (sixMonthsAgo); + + steve.Department = (dept); + dept.Salespersons.Add(steve); + + Salesperson max = new Salesperson(); + max.Name = ("max"); + max.Region = ("EMEA"); + max.HireDate = (nextMonth); + + max.Department = (dept); + dept.Salespersons.Add(max); + + await (session.SaveAsync(steve, cancellationToken)); + await (session.SaveAsync(max, cancellationToken)); + entitiesToCleanUp.Add(steve); + entitiesToCleanUp.Add(max); + + steveId = steve.Id; + + Category cat1 = new Category("test cat 1", lastMonth, nextMonth); + Category cat2 = new Category("test cat 2", sixMonthsAgo, fourMonthsAgo); + + Product product1 = new Product(); + product1.Name = ("Acme Hair Gel"); + product1.StockNumber = (123); + product1.EffectiveStartDate = (lastMonth); + product1.EffectiveEndDate = (nextMonth); + + product1.AddCategory(cat1); + product1.AddCategory(cat2); + + await (session.SaveAsync(product1, cancellationToken)); + entitiesToCleanUp.Add(product1); + prod1Id = product1.Id; + + Order order1 = new Order(); + order1.Buyer = "gavin"; + order1.Region = ("APAC"); + order1.PlacementDate = sixMonthsAgo; + order1.FulfillmentDate = fourMonthsAgo; + order1.Salesperson = steve; + order1.AddLineItem(product1, 500); + + await (session.SaveAsync(order1, cancellationToken)); + entitiesToCleanUp.Add(order1); + + Product product2 = new Product(); + product2.Name = ("Acme Super-Duper DTO Factory"); + product2.StockNumber = (124); + product2.EffectiveStartDate = (sixMonthsAgo); + product2.EffectiveEndDate = (DateTime.Today); + + Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); + product2.AddCategory(cat3); + + await (session.SaveAsync(product2, cancellationToken)); + entitiesToCleanUp.Add(product2); + + // An uncategorized product + Product product3 = new Product(); + product3.Name = ("Uncategorized product"); + await (session.SaveAsync(product3, cancellationToken)); + entitiesToCleanUp.Add(product3); + + Order order2 = new Order(); + order2.Buyer = "christian"; + order2.Region = ("EMEA"); + order2.PlacementDate = lastMonth; + order2.Salesperson = steve; + order2.AddLineItem(product2, -1); + + await (session.SaveAsync(order2, cancellationToken)); + entitiesToCleanUp.Add(order2); + + await (transaction.CommitAsync(cancellationToken)); + } + } - await (transaction.CommitAsync(cancellationToken)); - session.Close(); + public void Prepare() + { + using (var session = outer.OpenSession()) + using (var transaction = session.BeginTransaction()) + { + lastMonth = DateTime.Today.AddMonths(-1); + nextMonth = DateTime.Today.AddMonths(1); + + sixMonthsAgo = DateTime.Today.AddMonths(-6); + fourMonthsAgo = DateTime.Today.AddMonths(-4); + + Department dept = new Department(); + dept.Name = ("Sales"); + + session.Save(dept); + deptId = dept.Id; + entitiesToCleanUp.Add(dept); + + Salesperson steve = new Salesperson(); + steve.Name = ("steve"); + steve.Region = ("APAC"); + steve.HireDate = (sixMonthsAgo); + + steve.Department = (dept); + dept.Salespersons.Add(steve); + + Salesperson max = new Salesperson(); + max.Name = ("max"); + max.Region = ("EMEA"); + max.HireDate = (nextMonth); + + max.Department = (dept); + dept.Salespersons.Add(max); + + session.Save(steve); + session.Save(max); + entitiesToCleanUp.Add(steve); + entitiesToCleanUp.Add(max); + + steveId = steve.Id; + + Category cat1 = new Category("test cat 1", lastMonth, nextMonth); + Category cat2 = new Category("test cat 2", sixMonthsAgo, fourMonthsAgo); + + Product product1 = new Product(); + product1.Name = ("Acme Hair Gel"); + product1.StockNumber = (123); + product1.EffectiveStartDate = (lastMonth); + product1.EffectiveEndDate = (nextMonth); + + product1.AddCategory(cat1); + product1.AddCategory(cat2); + + session.Save(product1); + entitiesToCleanUp.Add(product1); + prod1Id = product1.Id; + + Order order1 = new Order(); + order1.Buyer = "gavin"; + order1.Region = ("APAC"); + order1.PlacementDate = sixMonthsAgo; + order1.FulfillmentDate = fourMonthsAgo; + order1.Salesperson = steve; + order1.AddLineItem(product1, 500); + + session.Save(order1); + entitiesToCleanUp.Add(order1); + + Product product2 = new Product(); + product2.Name = ("Acme Super-Duper DTO Factory"); + product2.StockNumber = (124); + product2.EffectiveStartDate = (sixMonthsAgo); + product2.EffectiveEndDate = (DateTime.Today); + + Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); + product2.AddCategory(cat3); + + session.Save(product2); + entitiesToCleanUp.Add(product2); + + // An uncategorized product + Product product3 = new Product(); + product3.Name = ("Uncategorized product"); + session.Save(product3); + entitiesToCleanUp.Add(product3); + + Order order2 = new Order(); + order2.Buyer = "christian"; + order2.Region = ("EMEA"); + order2.PlacementDate = lastMonth; + order2.Salesperson = steve; + order2.AddLineItem(product2, -1); + + session.Save(order2); + entitiesToCleanUp.Add(order2); + + transaction.Commit(); + } } public async Task ReleaseAsync(CancellationToken cancellationToken = default(CancellationToken)) { - ISession session = outer.OpenSession(); - ITransaction transaction = session.BeginTransaction(); - - foreach (object obj in entitiesToCleanUp) + using (var session = outer.OpenSession()) + using (var transaction = session.BeginTransaction()) { - await (session.DeleteAsync(obj, cancellationToken)); - } - await (transaction.CommitAsync(cancellationToken)); - session.Close(); + foreach (var obj in entitiesToCleanUp) + { + await (session.DeleteAsync(obj, cancellationToken)); + } + + await (transaction.CommitAsync(cancellationToken)); + } } public void Release() { - ISession session = outer.OpenSession(); - ITransaction transaction = session.BeginTransaction(); - - foreach (object obj in entitiesToCleanUp) + using (var session = outer.OpenSession()) + using (var transaction = session.BeginTransaction()) { - session.Delete(obj); - } - transaction.Commit(); - session.Close(); - } + foreach (var obj in entitiesToCleanUp) + { + session.Delete(obj); + } - public void Dispose() - { - Release(); + transaction.Commit(); + } } } } diff --git a/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs b/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs index 43075b56c63..e34d2a33c51 100644 --- a/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs +++ b/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs @@ -1,13 +1,10 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using log4net; using NHibernate.Cache; using NHibernate.Cache.Entry; using NHibernate.Criterion; -using NHibernate.Engine; -using NHibernate.Persister.Collection; using NHibernate.Transform; using NUnit.Framework; @@ -16,118 +13,119 @@ namespace NHibernate.Test.FilterTest [TestFixture] public class DynamicFilterTest : TestCase { - private ILog log = LogManager.GetLogger(typeof(DynamicFilterTest)); + private static readonly ILog log = LogManager.GetLogger(typeof(DynamicFilterTest)); + private TestData testData; - [Test] - public void SecondLevelCachedCollectionsFiltering() + protected override void OnSetUp() { - TestData testData = new TestData(this); + testData = new TestData(this); testData.Prepare(); + } - ISession session = OpenSession(); + protected override void OnTearDown() + { + testData.Release(); + } - // Force a collection into the second level cache, with its non-filtered elements - Salesperson sp = (Salesperson) session.Load(typeof(Salesperson), testData.steveId); - NHibernateUtil.Initialize(sp.Orders); - ICollectionPersister persister = ((ISessionFactoryImplementor) Sfi) + [Test] + public void SecondLevelCachedCollectionsFiltering() + { + var persister = Sfi .GetCollectionPersister(typeof(Salesperson).FullName + ".Orders"); - Assert.IsTrue(persister.HasCache, "No cache for collection"); - CacheKey cacheKey = - new CacheKey(testData.steveId, persister.KeyType, persister.Role, (ISessionFactoryImplementor) Sfi); - CollectionCacheEntry cachedData = (CollectionCacheEntry)persister.Cache.Cache.Get(cacheKey); - Assert.IsNotNull(cachedData, "collection was not in cache"); - - session.Close(); + var cacheKey = + new CacheKey(testData.steveId, persister.KeyType, persister.Role, Sfi); + CollectionCacheEntry cachedData; - session = OpenSession(); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - sp = (Salesperson) session.CreateQuery("from Salesperson as s where s.id = :id") - .SetInt64("id", testData.steveId) - .UniqueResult(); - Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); - - CollectionCacheEntry cachedData2 = (CollectionCacheEntry)persister.Cache.Cache.Get(cacheKey); - Assert.IsNotNull(cachedData2, "collection no longer in cache!"); - Assert.AreSame(cachedData, cachedData2, "Different cache values!"); - - session.Close(); + using (var session = OpenSession()) + { + // Force a collection into the second level cache, with its non-filtered elements + var sp = (Salesperson) session.Load(typeof(Salesperson), testData.steveId); + NHibernateUtil.Initialize(sp.Orders); + Assert.IsTrue(persister.HasCache, "No cache for collection"); + cachedData = (CollectionCacheEntry) persister.Cache.Cache.Get(cacheKey); + Assert.IsNotNull(cachedData, "collection was not in cache"); + } - session = OpenSession(); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - sp = (Salesperson) session.Load(typeof(Salesperson), testData.steveId); - Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); + using (var session = OpenSession()) + { + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); + var sp = (Salesperson) session.CreateQuery("from Salesperson as s where s.id = :id") + .SetInt64("id", testData.steveId) + .UniqueResult(); + Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); + + CollectionCacheEntry cachedData2 = (CollectionCacheEntry) persister.Cache.Cache.Get(cacheKey); + Assert.IsNotNull(cachedData2, "collection no longer in cache!"); + Assert.AreSame(cachedData, cachedData2, "Different cache values!"); + } - session.Close(); + using (var session = OpenSession()) + { + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); + var sp = (Salesperson) session.Load(typeof(Salesperson), testData.steveId); + Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache"); + } // Finally, make sure that the original cached version did not get over-written - session = OpenSession(); - sp = (Salesperson) session.Load(typeof(Salesperson), testData.steveId); - Assert.AreEqual(2, sp.Orders.Count, "Actual cached version got over-written"); - - session.Close(); - testData.Release(); + using (var session = OpenSession()) + { + var sp = (Salesperson) session.Load(typeof(Salesperson), testData.steveId); + Assert.AreEqual(2, sp.Orders.Count, "Actual cached version got over-written"); + } } [Test] public void CombinedClassAndCollectionFiltersEnabled() { - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("regionlist").SetParameterList("regions", new string[] {"LA", "APAC"}); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - - // test retreival through hql with the collection as non-eager - IList salespersons = session.CreateQuery("select s from Salesperson as s").List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - Salesperson sp = (Salesperson) salespersons[0]; - Assert.AreEqual(1, sp.Orders.Count, "Incorrect order count"); - - session.Clear(); - - // test retreival through hql with the collection join fetched - salespersons = session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - sp = (Salesperson) salespersons[0]; - Assert.AreEqual(sp.Orders.Count, 1, "Incorrect order count"); - - session.Close(); - testData.Release(); + using (var session = OpenSession()) + { + session.EnableFilter("regionlist").SetParameterList("regions", new[] { "LA", "APAC" }); + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); + + // test retreival through hql with the collection as non-eager + IList salespersons = session.CreateQuery("select s from Salesperson as s").List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + Salesperson sp = (Salesperson) salespersons[0]; + Assert.AreEqual(1, sp.Orders.Count, "Incorrect order count"); + + session.Clear(); + + // test retreival through hql with the collection join fetched + salespersons = session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + sp = (Salesperson) salespersons[0]; + Assert.AreEqual(sp.Orders.Count, 1, "Incorrect order count"); + } } [Test] public void FiltersWithQueryCache() { - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("regionlist").SetParameterList("regions", new string[] {"LA", "APAC"}); - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - - // test retreival through hql with the collection as non-eager - IList salespersons = session.CreateQuery("select s from Salesperson as s").SetCacheable(true).List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + using (var session = OpenSession()) + { + session.EnableFilter("regionlist").SetParameterList("regions", new[] { "LA", "APAC" }); + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth); - // Try a second time, to make use of query cache - salespersons = session.CreateQuery("select s from Salesperson as s").SetCacheable(true).List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + // test retreival through hql with the collection as non-eager + IList salespersons = session.CreateQuery("select s from Salesperson as s").SetCacheable(true).List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - session.Clear(); + // Try a second time, to make use of query cache + salespersons = session.CreateQuery("select s from Salesperson as s").SetCacheable(true).List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - // test retreival through hql with the collection join fetched - salespersons = - session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + session.Clear(); - // A second time, to make use of query cache - salespersons = - session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + // test retreival through hql with the collection join fetched + salespersons = + session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - session.Close(); - testData.Release(); + // A second time, to make use of query cache + salespersons = + session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").SetCacheable(true).List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + } } [Test] @@ -137,27 +135,23 @@ public void HqlFilters() // HQL test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting HQL filter tests"); - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("region").SetParameter("region", "APAC"); - - session.EnableFilter("effectiveDate") - .SetParameter("asOfDate", testData.lastMonth); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); - log.Info("HQL against Salesperson..."); - IList results = session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").List(); - Assert.IsTrue(results.Count == 1, "Incorrect filtered HQL result count [" + results.Count + "]"); - Salesperson result = (Salesperson) results[0]; - Assert.IsTrue(result.Orders.Count == 1, "Incorrect collectionfilter count"); + session.EnableFilter("effectiveDate") + .SetParameter("asOfDate", testData.lastMonth); - log.Info("HQL against Product..."); - results = session.CreateQuery("from Product as p where p.StockNumber = ?").SetInt32(0, 124).List(); - Assert.IsTrue(results.Count == 1); + log.Info("HQL against Salesperson..."); + IList results = session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").List(); + Assert.IsTrue(results.Count == 1, "Incorrect filtered HQL result count [" + results.Count + "]"); + Salesperson result = (Salesperson) results[0]; + Assert.IsTrue(result.Orders.Count == 1, "Incorrect collectionfilter count"); - session.Close(); - testData.Release(); + log.Info("HQL against Product..."); + results = session.CreateQuery("from Product as p where p.StockNumber = ?").SetInt32(0, 124).List(); + Assert.IsTrue(results.Count == 1); + } } [Test] @@ -167,63 +161,55 @@ public void CriteriaQueryFilters() // Criteria-query test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting Criteria-query filter tests"); - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("region").SetParameter("region", "APAC"); - - session.EnableFilter("fulfilledOrders") - .SetParameter("asOfDate", testData.lastMonth); - - session.EnableFilter("effectiveDate") - .SetParameter("asOfDate", testData.lastMonth); - - log.Info("Criteria query against Salesperson..."); - IList salespersons = session.CreateCriteria(typeof(Salesperson)) - .SetFetchMode("orders", FetchMode.Join) - .List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); - Assert.AreEqual(1, ((Salesperson) salespersons[0]).Orders.Count, "Incorrect order count"); - - log.Info("Criteria query against Product..."); - IList products = session.CreateCriteria(typeof(Product)) - .Add(Expression.Eq("StockNumber", 124)) - .List(); - Assert.AreEqual(1, products.Count, "Incorrect product count"); - session.Close(); - testData.Release(); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); + + session.EnableFilter("fulfilledOrders") + .SetParameter("asOfDate", testData.lastMonth); + + session.EnableFilter("effectiveDate") + .SetParameter("asOfDate", testData.lastMonth); + + log.Info("Criteria query against Salesperson..."); + IList salespersons = session.CreateCriteria(typeof(Salesperson)) + .SetFetchMode("orders", FetchMode.Join) + .List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + Assert.AreEqual(1, ((Salesperson) salespersons[0]).Orders.Count, "Incorrect order count"); + + log.Info("Criteria query against Product..."); + IList products = session.CreateCriteria(typeof(Product)) + .Add(Expression.Eq("StockNumber", 124)) + .List(); + Assert.AreEqual(1, products.Count, "Incorrect product count"); + } } [Test] public void CriteriaControl() { - using (var testData = new TestData(this)) - { - testData.Prepare(); - - // the subquery... - var subquery = DetachedCriteria - .For() - .SetProjection(Property.ForName("Name")); + // the subquery... + var subquery = DetachedCriteria + .For() + .SetProjection(Property.ForName("Name")); - using (var session = OpenSession()) - using (var transaction = session.BeginTransaction()) - { - session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth.Date); - session.EnableFilter("regionlist").SetParameter("regions", "APAC"); + using (var session = OpenSession()) + using (var transaction = session.BeginTransaction()) + { + session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth.Date); + session.EnableFilter("regionlist").SetParameter("regions", "APAC"); - var result = session - .CreateCriteria() - .Add(Subqueries.In("steve", subquery)) - .List(); + var result = session + .CreateCriteria() + .Add(Subqueries.In("steve", subquery)) + .List(); - Assert.That(result.Count, Is.EqualTo(1)); + Assert.That(result.Count, Is.EqualTo(1)); - transaction.Commit(); - } + transaction.Commit(); } } @@ -234,85 +220,81 @@ public void CriteriaSubqueryWithFilters() // Criteria-subquery test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting Criteria-subquery filter tests"); - using (var testData = new TestData(this)) - { - testData.Prepare(); - using (var session = OpenSession()) - { - session.EnableFilter("region").SetParameter("region", "APAC"); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); - log.Info("Criteria query against Department with a subquery on Salesperson in the APAC reqion..."); - var salespersonSubquery = DetachedCriteria.For() - .Add(Restrictions.Eq("Name", "steve")) - .SetProjection(Property.ForName("Department")); + log.Info("Criteria query against Department with a subquery on Salesperson in the APAC reqion..."); + var salespersonSubquery = DetachedCriteria.For() + .Add(Restrictions.Eq("Name", "steve")) + .SetProjection(Property.ForName("Department")); - var departmentsQuery = session.CreateCriteria(). - Add(Subqueries.PropertyIn("Id", salespersonSubquery)); - var departments = departmentsQuery.List(); + var departmentsQuery = session.CreateCriteria(). + Add(Subqueries.PropertyIn("Id", salespersonSubquery)); + var departments = departmentsQuery.List(); - Assert.That(departments.Count, Is.EqualTo(1), "Incorrect department count"); + Assert.That(departments.Count, Is.EqualTo(1), "Incorrect department count"); - log.Info("Criteria query against Department with a subquery on Salesperson in the FooBar reqion..."); + log.Info("Criteria query against Department with a subquery on Salesperson in the FooBar reqion..."); - session.EnableFilter("region").SetParameter("region", "Foobar"); - departments = departmentsQuery.List(); + session.EnableFilter("region").SetParameter("region", "Foobar"); + departments = departmentsQuery.List(); - Assert.That(departments.Count, Is.EqualTo(0), "Incorrect department count"); + Assert.That(departments.Count, Is.EqualTo(0), "Incorrect department count"); - log.Info("Criteria query against Order with a subquery for line items with a subquery on product and sold by a given sales person..."); - session.EnableFilter("region").SetParameter("region", "APAC"); + log.Info("Criteria query against Order with a subquery for line items with a subquery on product and sold by a given sales person..."); + session.EnableFilter("region").SetParameter("region", "APAC"); - var lineItemSubquery = DetachedCriteria.For() - .Add(Restrictions.Ge("Quantity", 1L)) - .CreateCriteria("Product") - .Add(Restrictions.Eq("Name", "Acme Hair Gel")) - .SetProjection(Property.ForName("Id")); + var lineItemSubquery = DetachedCriteria.For() + .Add(Restrictions.Ge("Quantity", 1L)) + .CreateCriteria("Product") + .Add(Restrictions.Eq("Name", "Acme Hair Gel")) + .SetProjection(Property.ForName("Id")); - var orders = session.CreateCriteria() - .Add(Subqueries.Exists(lineItemSubquery)) - .Add(Restrictions.Eq("Buyer", "gavin")) - .List(); + var orders = session.CreateCriteria() + .Add(Subqueries.Exists(lineItemSubquery)) + .Add(Restrictions.Eq("Buyer", "gavin")) + .List(); - Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); + Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); - log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); - session.EnableFilter("region").SetParameter("region", "APAC"); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.lastMonth.Date); + log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); + session.EnableFilter("region").SetParameter("region", "APAC"); + session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.lastMonth.Date); - var productSubquery = DetachedCriteria.For() - . - Add(Restrictions.Eq("Name", "Acme Hair Gel")) - .SetProjection(Property.ForName("id")); + var productSubquery = DetachedCriteria.For() + . + Add(Restrictions.Eq("Name", "Acme Hair Gel")) + .SetProjection(Property.ForName("id")); - lineItemSubquery = DetachedCriteria.For() - .Add(Restrictions.Ge("Quantity", 1L)) - .CreateCriteria("Product") - .Add(Subqueries.PropertyIn("Id", productSubquery)) - .SetProjection(Property.ForName("Id")); + lineItemSubquery = DetachedCriteria.For() + .Add(Restrictions.Ge("Quantity", 1L)) + .CreateCriteria("Product") + .Add(Subqueries.PropertyIn("Id", productSubquery)) + .SetProjection(Property.ForName("Id")); - orders = session - .CreateCriteria() - .Add(Subqueries.Exists(lineItemSubquery)) - .Add(Restrictions.Eq("Buyer", "gavin")) - .List(); + orders = session + .CreateCriteria() + .Add(Subqueries.Exists(lineItemSubquery)) + .Add(Restrictions.Eq("Buyer", "gavin")) + .List(); - Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); + Assert.That(orders.Count, Is.EqualTo(1), "Incorrect orders count"); - log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); - session.EnableFilter("region").SetParameter("region", "APAC"); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.fourMonthsAgo.Date); + log.Info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); + session.EnableFilter("region").SetParameter("region", "APAC"); + session.EnableFilter("effectiveDate").SetParameter("asOfDate", testData.fourMonthsAgo.Date); - orders = session.CreateCriteria() - .Add(Subqueries.Exists(lineItemSubquery)) - .Add(Restrictions.Eq("Buyer", "gavin")) - .List(); + orders = session.CreateCriteria() + .Add(Subqueries.Exists(lineItemSubquery)) + .Add(Restrictions.Eq("Buyer", "gavin")) + .List(); - Assert.That(orders.Count, Is.EqualTo(0), "Incorrect orders count"); + Assert.That(orders.Count, Is.EqualTo(0), "Incorrect orders count"); - session.Close(); - } + session.Close(); } } @@ -324,19 +306,15 @@ public void GetFilters() // Get() test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting get() filter tests (eager assoc. fetching)."); - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("region").SetParameter("region", "APAC"); - - log.Info("Performing get()..."); - Salesperson salesperson = (Salesperson) session.Get(typeof(Salesperson), testData.steveId); - Assert.IsNotNull(salesperson); - Assert.AreEqual(1, salesperson.Orders.Count, "Incorrect order count"); + using (var session = OpenSession()) + { + session.EnableFilter("region").SetParameter("region", "APAC"); - session.Close(); - testData.Release(); + log.Info("Performing get()..."); + Salesperson salesperson = (Salesperson) session.Get(typeof(Salesperson), testData.steveId); + Assert.IsNotNull(salesperson); + Assert.AreEqual(1, salesperson.Orders.Count, "Incorrect order count"); + } } [Test] @@ -346,20 +324,16 @@ public void OneToManyFilters() // one-to-many loading tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting one-to-many collection loader filter tests."); - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("seniorSalespersons") - .SetParameter("asOfDate", testData.lastMonth); - - log.Info("Performing Load of Department..."); - Department department = (Department) session.Load(typeof(Department), testData.deptId); - ISet salespersons = department.Salespersons; - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + using (var session = OpenSession()) + { + session.EnableFilter("seniorSalespersons") + .SetParameter("asOfDate", testData.lastMonth); - session.Close(); - testData.Release(); + log.Info("Performing Load of Department..."); + Department department = (Department) session.Load(typeof(Department), testData.deptId); + ISet salespersons = department.Salespersons; + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + } } [Test] @@ -369,246 +343,215 @@ public void InStyleFilterParameter() // one-to-many loading tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log.Info("Starting one-to-many collection loader filter tests."); - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("regionlist") - .SetParameterList("regions", new string[] {"LA", "APAC"}); - - log.Debug("Performing query of Salespersons"); - IList salespersons = session.CreateQuery("from Salesperson").List(); - Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + using (var session = OpenSession()) + { + session.EnableFilter("regionlist") + .SetParameterList("regions", new [] { "LA", "APAC" }); - session.Close(); - testData.Release(); + log.Debug("Performing query of Salespersons"); + IList salespersons = session.CreateQuery("from Salesperson").List(); + Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count"); + } } - [Test] + [Test] public void ManyToManyFilterOnCriteria() { - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - - Product prod = (Product) session.CreateCriteria(typeof(Product)) - .SetResultTransformer(new DistinctRootEntityResultTransformer()) - .Add(Expression.Eq("id", testData.prod1Id)) - .UniqueResult(); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - Assert.IsNotNull(prod); - Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter"); + Product prod = (Product) session.CreateCriteria(typeof(Product)) + .SetResultTransformer(new DistinctRootEntityResultTransformer()) + .Add(Expression.Eq("id", testData.prod1Id)) + .UniqueResult(); - session.Close(); - testData.Release(); + Assert.IsNotNull(prod); + Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter"); + } } [Test] public void ManyToManyFilterOnLoad() { - TestData testData = new TestData(this); - testData.Prepare(); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); + Product prod = (Product) session.Get(typeof(Product), testData.prod1Id); - Product prod = (Product) session.Get(typeof(Product), testData.prod1Id); + //long initLoadCount = sessions.Statistics.CollectionLoadCount; + //long initFetchCount = sessions.Statistics.CollectionFetchCount; - //long initLoadCount = sessions.Statistics.CollectionLoadCount; - //long initFetchCount = sessions.Statistics.CollectionFetchCount; + // should already have been initialized... + Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories)); + int size = prod.Categories.Count; + Assert.AreEqual(1, size, "Incorrect filtered collection count"); - // should already have been initialized... - Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories)); - int size = prod.Categories.Count; - Assert.AreEqual(1, size, "Incorrect filtered collection count"); + //long currLoadCount = sessions.Statistics.CollectionLoadCount; + //long currFetchCount = sessions.Statistics.CollectionFetchCount; - //long currLoadCount = sessions.Statistics.CollectionLoadCount; - //long currFetchCount = sessions.Statistics.CollectionFetchCount; + //Assert.IsTrue( + // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), + // "Load with join fetch of many-to-many did not trigger join fetch" + // ); - //Assert.IsTrue( - // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), - // "Load with join fetch of many-to-many did not trigger join fetch" - // ); + // make sure we did not get back a collection of proxies + //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; - // make sure we did not get back a collection of proxies - //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; + foreach (Category cat in prod.Categories) + { + Assert.IsTrue( + NHibernateUtil.IsInitialized(cat), + "Load with join fetch of many-to-many did not trigger *complete* join fetch"); + //Console.WriteLine(" ===> " + cat.Name); + } + //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - foreach (Category cat in prod.Categories) - { - Assert.IsTrue(NHibernateUtil.IsInitialized(cat), - "Load with join fetch of many-to-many did not trigger *complete* join fetch"); - //Console.WriteLine(" ===> " + cat.Name); + //Assert.IsTrue( + // (initEntityLoadCount == currEntityLoadCount), + // "Load with join fetch of many-to-many did not trigger *complete* join fetch" + // ); } - //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - - //Assert.IsTrue( - // (initEntityLoadCount == currEntityLoadCount), - // "Load with join fetch of many-to-many did not trigger *complete* join fetch" - // ); - - session.Close(); - testData.Release(); } [Test] public void ManyToManyOnCollectionLoadAfterHQL() { - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - - // Force the categories to not get initialized here - IList result = session.CreateQuery("from Product as p where p.id = :id") - .SetInt64("id", testData.prod1Id) - .List(); - Assert.IsTrue(result.Count > 0, "No products returned from HQL"); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - Product prod = (Product) result[0]; - Assert.IsNotNull(prod); - Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter on collection Load"); + // Force the categories to not get initialized here + IList result = session.CreateQuery("from Product as p where p.id = :id") + .SetInt64("id", testData.prod1Id) + .List(); + Assert.IsTrue(result.Count > 0, "No products returned from HQL"); - session.Close(); - testData.Release(); + Product prod = (Product) result[0]; + Assert.IsNotNull(prod); + Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter on collection Load"); + } } [Test] public void ManyToManyFilterOnQuery() { - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - - IList result = session.CreateQuery("from Product p inner join fetch p.Categories").List(); - Assert.IsTrue(result.Count > 0, "No products returned from HQL many-to-many filter case"); + using (var session = OpenSession()) + { + session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); - Product prod = (Product) result[0]; + IList result = session.CreateQuery("from Product p inner join fetch p.Categories").List(); + Assert.IsTrue(result.Count > 0, "No products returned from HQL many-to-many filter case"); - Assert.IsNotNull(prod); - Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter with HQL"); + Product prod = (Product) result[0]; - session.Close(); - testData.Release(); + Assert.IsNotNull(prod); + Assert.AreEqual(1, prod.Categories.Count, "Incorrect Product.categories count for filter with HQL"); + } } [Test] public void ManyToManyBase() { - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); - - Product prod = (Product) session.Get(typeof(Product), testData.prod1Id); - - // TODO H3: Statistics - //long initLoadCount = sessions.Statistics.CollectionLoadCount; - //long initFetchCount = sessions.Statistics.CollectionFetchCount; - - // should already have been initialized... - Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories), - "Load with join fetch of many-to-many did not trigger join fetch"); - int size = prod.Categories.Count; - Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); - - //long currLoadCount = sessions.Statistics.CollectionLoadCount; - //long currFetchCount = sessions.Statistics.CollectionFetchCount; - - //Assert.IsTrue( - // ( initLoadCount == currLoadCount ) && ( initFetchCount == currFetchCount ), - // "Load with join fetch of many-to-many did not trigger join fetch" - //); - - // make sure we did not get back a collection of proxies - // TODO H3: statistics - //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; - foreach (Category cat in prod.Categories) + using (var session = OpenSession()) { - Assert.IsTrue(NHibernateUtil.IsInitialized(cat), - "Load with join fetch of many-to-many did not trigger *complete* join fetch"); - //Console.WriteLine(" ===> " + cat.Name); - } - //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - - //Assert.IsTrue( - // ( initEntityLoadCount == currEntityLoadCount ), - // "Load with join fetch of many-to-many did not trigger *complete* join fetch" - //); + Product prod = (Product) session.Get(typeof(Product), testData.prod1Id); + + // TODO H3: Statistics + //long initLoadCount = sessions.Statistics.CollectionLoadCount; + //long initFetchCount = sessions.Statistics.CollectionFetchCount; + + // should already have been initialized... + Assert.IsTrue( + NHibernateUtil.IsInitialized(prod.Categories), + "Load with join fetch of many-to-many did not trigger join fetch"); + int size = prod.Categories.Count; + Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); + + //long currLoadCount = sessions.Statistics.CollectionLoadCount; + //long currFetchCount = sessions.Statistics.CollectionFetchCount; + + //Assert.IsTrue( + // ( initLoadCount == currLoadCount ) && ( initFetchCount == currFetchCount ), + // "Load with join fetch of many-to-many did not trigger join fetch" + //); + + // make sure we did not get back a collection of proxies + // TODO H3: statistics + //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; + foreach (Category cat in prod.Categories) + { + Assert.IsTrue( + NHibernateUtil.IsInitialized(cat), + "Load with join fetch of many-to-many did not trigger *complete* join fetch"); + //Console.WriteLine(" ===> " + cat.Name); + } + //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - session.Close(); - testData.Release(); + //Assert.IsTrue( + // ( initEntityLoadCount == currEntityLoadCount ), + // "Load with join fetch of many-to-many did not trigger *complete* join fetch" + //); + } } [Test] public void ManyToManyBaseThruCriteria() { - TestData testData = new TestData(this); - testData.Prepare(); - - ISession session = OpenSession(); + using (var session = OpenSession()) + { + IList result = session.CreateCriteria(typeof(Product)) + .Add(Expression.Eq("id", testData.prod1Id)) + .List(); - IList result = session.CreateCriteria(typeof(Product)) - .Add(Expression.Eq("id", testData.prod1Id)) - .List(); + Product prod = (Product) result[0]; - Product prod = (Product) result[0]; + //long initLoadCount = sessions.Statistics.CollectionLoadCount; + //long initFetchCount = sessions.Statistics.CollectionFetchCount; - //long initLoadCount = sessions.Statistics.CollectionLoadCount; - //long initFetchCount = sessions.Statistics.CollectionFetchCount; + // should already have been initialized... + Assert.IsTrue( + NHibernateUtil.IsInitialized(prod.Categories), + "Load with join fetch of many-to-many did not trigger join fetch"); + int size = prod.Categories.Count; + Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); - // should already have been initialized... - Assert.IsTrue(NHibernateUtil.IsInitialized(prod.Categories), - "Load with join fetch of many-to-many did not trigger join fetch"); - int size = prod.Categories.Count; - Assert.AreEqual(2, size, "Incorrect non-filtered collection count"); + //long currLoadCount = sessions.Statistics.CollectionLoadCount; + //long currFetchCount = sessions.Statistics.CollectionFetchCount; - //long currLoadCount = sessions.Statistics.CollectionLoadCount; - //long currFetchCount = sessions.Statistics.CollectionFetchCount; + //Assert.IsTrue( + // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), + // "Load with join fetch of many-to-many did not trigger join fetch" + // ); - //Assert.IsTrue( - // (initLoadCount == currLoadCount) && (initFetchCount == currFetchCount), - // "Load with join fetch of many-to-many did not trigger join fetch" - // ); + // make sure we did not get back a collection of proxies + //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; + foreach (Category cat in prod.Categories) + { + Assert.IsTrue( + NHibernateUtil.IsInitialized(cat), + "Load with join fetch of many-to-many did not trigger *complete* join fetch"); + //Console.WriteLine(" ===> " + cat.Name); + } + //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - // make sure we did not get back a collection of proxies - //long initEntityLoadCount = sessions.Statistics.EntityLoadCount; - foreach (Category cat in prod.Categories) - { - Assert.IsTrue(NHibernateUtil.IsInitialized(cat), - "Load with join fetch of many-to-many did not trigger *complete* join fetch"); - //Console.WriteLine(" ===> " + cat.Name); + //Assert.IsTrue( + // (initEntityLoadCount == currEntityLoadCount), + // "Load with join fetch of many-to-many did not trigger *complete* join fetch" + // ); } - //long currEntityLoadCount = sessions.Statistics.EntityLoadCount; - - //Assert.IsTrue( - // (initEntityLoadCount == currEntityLoadCount), - // "Load with join fetch of many-to-many did not trigger *complete* join fetch" - // ); - - session.Close(); - testData.Release(); } protected override string MappingsAssembly => "NHibernate.Test"; - protected override IList Mappings + protected override IList Mappings => new [] { - get - { - return new string[] - { - "FilterTest.defs.hbm.xml", - "FilterTest.classes.hbm.xml", - }; - } - } + "FilterTest.defs.hbm.xml", + "FilterTest.classes.hbm.xml", + }; - private class TestData:IDisposable + private class TestData { public long steveId; public long deptId; @@ -625,125 +568,121 @@ public TestData(DynamicFilterTest outer) this.outer = outer; } - public IList entitiesToCleanUp = new List(); + private readonly IList entitiesToCleanUp = new List(); public void Prepare() { - ISession session = outer.OpenSession(); - ITransaction transaction = session.BeginTransaction(); - - lastMonth = DateTime.Today.AddMonths(-1); - nextMonth = DateTime.Today.AddMonths(1); + using (var session = outer.OpenSession()) + using (var transaction = session.BeginTransaction()) + { + lastMonth = DateTime.Today.AddMonths(-1); + nextMonth = DateTime.Today.AddMonths(1); - sixMonthsAgo = DateTime.Today.AddMonths(-6); - fourMonthsAgo = DateTime.Today.AddMonths(-4); + sixMonthsAgo = DateTime.Today.AddMonths(-6); + fourMonthsAgo = DateTime.Today.AddMonths(-4); - Department dept = new Department(); - dept.Name = ("Sales"); + Department dept = new Department(); + dept.Name = ("Sales"); - session.Save(dept); - deptId = dept.Id; - entitiesToCleanUp.Add(dept); + session.Save(dept); + deptId = dept.Id; + entitiesToCleanUp.Add(dept); - Salesperson steve = new Salesperson(); - steve.Name = ("steve"); - steve.Region = ("APAC"); - steve.HireDate = (sixMonthsAgo); + Salesperson steve = new Salesperson(); + steve.Name = ("steve"); + steve.Region = ("APAC"); + steve.HireDate = (sixMonthsAgo); - steve.Department = (dept); - dept.Salespersons.Add(steve); + steve.Department = (dept); + dept.Salespersons.Add(steve); - Salesperson max = new Salesperson(); - max.Name = ("max"); - max.Region = ("EMEA"); - max.HireDate = (nextMonth); + Salesperson max = new Salesperson(); + max.Name = ("max"); + max.Region = ("EMEA"); + max.HireDate = (nextMonth); - max.Department = (dept); - dept.Salespersons.Add(max); + max.Department = (dept); + dept.Salespersons.Add(max); - session.Save(steve); - session.Save(max); - entitiesToCleanUp.Add(steve); - entitiesToCleanUp.Add(max); + session.Save(steve); + session.Save(max); + entitiesToCleanUp.Add(steve); + entitiesToCleanUp.Add(max); - steveId = steve.Id; + steveId = steve.Id; - Category cat1 = new Category("test cat 1", lastMonth, nextMonth); - Category cat2 = new Category("test cat 2", sixMonthsAgo, fourMonthsAgo); + Category cat1 = new Category("test cat 1", lastMonth, nextMonth); + Category cat2 = new Category("test cat 2", sixMonthsAgo, fourMonthsAgo); - Product product1 = new Product(); - product1.Name = ("Acme Hair Gel"); - product1.StockNumber = (123); - product1.EffectiveStartDate = (lastMonth); - product1.EffectiveEndDate = (nextMonth); + Product product1 = new Product(); + product1.Name = ("Acme Hair Gel"); + product1.StockNumber = (123); + product1.EffectiveStartDate = (lastMonth); + product1.EffectiveEndDate = (nextMonth); - product1.AddCategory(cat1); - product1.AddCategory(cat2); + product1.AddCategory(cat1); + product1.AddCategory(cat2); - session.Save(product1); - entitiesToCleanUp.Add(product1); - prod1Id = product1.Id; + session.Save(product1); + entitiesToCleanUp.Add(product1); + prod1Id = product1.Id; - Order order1 = new Order(); - order1.Buyer = "gavin"; - order1.Region = ("APAC"); - order1.PlacementDate = sixMonthsAgo; - order1.FulfillmentDate = fourMonthsAgo; - order1.Salesperson = steve; - order1.AddLineItem(product1, 500); + Order order1 = new Order(); + order1.Buyer = "gavin"; + order1.Region = ("APAC"); + order1.PlacementDate = sixMonthsAgo; + order1.FulfillmentDate = fourMonthsAgo; + order1.Salesperson = steve; + order1.AddLineItem(product1, 500); - session.Save(order1); - entitiesToCleanUp.Add(order1); + session.Save(order1); + entitiesToCleanUp.Add(order1); - Product product2 = new Product(); - product2.Name = ("Acme Super-Duper DTO Factory"); - product2.StockNumber = (124); - product2.EffectiveStartDate = (sixMonthsAgo); - product2.EffectiveEndDate = (DateTime.Today); + Product product2 = new Product(); + product2.Name = ("Acme Super-Duper DTO Factory"); + product2.StockNumber = (124); + product2.EffectiveStartDate = (sixMonthsAgo); + product2.EffectiveEndDate = (DateTime.Today); - Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); - product2.AddCategory(cat3); + Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); + product2.AddCategory(cat3); - session.Save(product2); - entitiesToCleanUp.Add(product2); + session.Save(product2); + entitiesToCleanUp.Add(product2); - // An uncategorized product - Product product3 = new Product(); - product3.Name = ("Uncategorized product"); - session.Save(product3); - entitiesToCleanUp.Add(product3); + // An uncategorized product + Product product3 = new Product(); + product3.Name = ("Uncategorized product"); + session.Save(product3); + entitiesToCleanUp.Add(product3); - Order order2 = new Order(); - order2.Buyer = "christian"; - order2.Region = ("EMEA"); - order2.PlacementDate = lastMonth; - order2.Salesperson = steve; - order2.AddLineItem(product2, -1); + Order order2 = new Order(); + order2.Buyer = "christian"; + order2.Region = ("EMEA"); + order2.PlacementDate = lastMonth; + order2.Salesperson = steve; + order2.AddLineItem(product2, -1); - session.Save(order2); - entitiesToCleanUp.Add(order2); + session.Save(order2); + entitiesToCleanUp.Add(order2); - transaction.Commit(); - session.Close(); + transaction.Commit(); + } } public void Release() { - ISession session = outer.OpenSession(); - ITransaction transaction = session.BeginTransaction(); - - foreach (object obj in entitiesToCleanUp) + using (var session = outer.OpenSession()) + using (var transaction = session.BeginTransaction()) { - session.Delete(obj); - } - transaction.Commit(); - session.Close(); - } + foreach (var obj in entitiesToCleanUp) + { + session.Delete(obj); + } - public void Dispose() - { - Release(); + transaction.Commit(); + } } } } From a6c4a5ae84275811e21508b1bf0506ed4aa76be8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Tue, 13 Mar 2018 15:04:36 +0100 Subject: [PATCH 2/2] Fix IFilter.SetParameterList not supporting HashSet arguments. Fixes #1585 Co-authored-by: Alexander Zaytsev --- .../Async/FilterTest/DynamicFilterTest.cs | 39 +++++++++++++++++++ .../FilterTest/DynamicFilterTest.cs | 35 +++++++++++++++++ src/NHibernate.Test/FilterTest/Product.cs | 2 + .../FilterTest/classes.hbm.xml | 5 ++- src/NHibernate.Test/FilterTest/defs.hbm.xml | 6 ++- .../Engine/Query/NativeSQLQueryPlan.cs | 11 ++---- src/NHibernate/Impl/FilterImpl.cs | 24 +++++++++--- src/NHibernate/Loader/Loader.cs | 11 ++---- 8 files changed, 112 insertions(+), 21 deletions(-) diff --git a/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs b/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs index 59133287cce..e8a61f2b160 100644 --- a/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs +++ b/src/NHibernate.Test/Async/FilterTest/DynamicFilterTest.cs @@ -366,6 +366,35 @@ public async Task InStyleFilterParameterAsync() } } + [Test] + public void InStyleFilterParameterWithHashSetAsync() + { + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // one-to-many loading tests + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + log.Info("Starting one-to-many collection loader filter tests with HashSet."); + using (var session = OpenSession()) + { + Assert.Multiple( + async () => + { + session.EnableFilter("regionlist") + .SetParameterList("regions", new HashSet { "LA", "APAC" }); + + log.Debug("Performing query of Salespersons"); + var salespersons = await (session.CreateQuery("from Salesperson").ListAsync()); + Assert.That(salespersons.Count, Is.EqualTo(1), "Incorrect salesperson count"); + + session.EnableFilter("guidlist") + .SetParameterList("guids", new HashSet { testData.Product1Guid, testData.Product2Guid }); + + log.Debug("Performing query of Products"); + var products = await (session.CreateQuery("from Product").ListAsync()); + Assert.That(products.Count, Is.EqualTo(2), "Incorrect product count"); + }); + } + } + [Test] public async Task ManyToManyFilterOnCriteriaAsync() { @@ -572,6 +601,8 @@ private class TestData public DateTime nextMonth; public DateTime sixMonthsAgo; public DateTime fourMonthsAgo; + public Guid Product1Guid; + public Guid Product2Guid; private DynamicFilterTestAsync outer; @@ -631,6 +662,8 @@ public TestData(DynamicFilterTestAsync outer) product1.StockNumber = (123); product1.EffectiveStartDate = (lastMonth); product1.EffectiveEndDate = (nextMonth); + product1.ProductGuid = Guid.NewGuid(); + Product1Guid = product1.ProductGuid; product1.AddCategory(cat1); product1.AddCategory(cat2); @@ -655,6 +688,8 @@ public TestData(DynamicFilterTestAsync outer) product2.StockNumber = (124); product2.EffectiveStartDate = (sixMonthsAgo); product2.EffectiveEndDate = (DateTime.Today); + product2.ProductGuid = Guid.NewGuid(); + Product2Guid = product2.ProductGuid; Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); product2.AddCategory(cat3); @@ -731,6 +766,8 @@ public void Prepare() product1.StockNumber = (123); product1.EffectiveStartDate = (lastMonth); product1.EffectiveEndDate = (nextMonth); + product1.ProductGuid = Guid.NewGuid(); + Product1Guid = product1.ProductGuid; product1.AddCategory(cat1); product1.AddCategory(cat2); @@ -755,6 +792,8 @@ public void Prepare() product2.StockNumber = (124); product2.EffectiveStartDate = (sixMonthsAgo); product2.EffectiveEndDate = (DateTime.Today); + product2.ProductGuid = Guid.NewGuid(); + Product2Guid = product2.ProductGuid; Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); product2.AddCategory(cat3); diff --git a/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs b/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs index e34d2a33c51..50917707288 100644 --- a/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs +++ b/src/NHibernate.Test/FilterTest/DynamicFilterTest.cs @@ -354,6 +354,35 @@ public void InStyleFilterParameter() } } + [Test] + public void InStyleFilterParameterWithHashSet() + { + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // one-to-many loading tests + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + log.Info("Starting one-to-many collection loader filter tests with HashSet."); + using (var session = OpenSession()) + { + Assert.Multiple( + () => + { + session.EnableFilter("regionlist") + .SetParameterList("regions", new HashSet { "LA", "APAC" }); + + log.Debug("Performing query of Salespersons"); + var salespersons = session.CreateQuery("from Salesperson").List(); + Assert.That(salespersons.Count, Is.EqualTo(1), "Incorrect salesperson count"); + + session.EnableFilter("guidlist") + .SetParameterList("guids", new HashSet { testData.Product1Guid, testData.Product2Guid }); + + log.Debug("Performing query of Products"); + var products = session.CreateQuery("from Product").List(); + Assert.That(products.Count, Is.EqualTo(2), "Incorrect product count"); + }); + } + } + [Test] public void ManyToManyFilterOnCriteria() { @@ -560,6 +589,8 @@ private class TestData public DateTime nextMonth; public DateTime sixMonthsAgo; public DateTime fourMonthsAgo; + public Guid Product1Guid; + public Guid Product2Guid; private DynamicFilterTest outer; @@ -619,6 +650,8 @@ public void Prepare() product1.StockNumber = (123); product1.EffectiveStartDate = (lastMonth); product1.EffectiveEndDate = (nextMonth); + product1.ProductGuid = Guid.NewGuid(); + Product1Guid = product1.ProductGuid; product1.AddCategory(cat1); product1.AddCategory(cat2); @@ -643,6 +676,8 @@ public void Prepare() product2.StockNumber = (124); product2.EffectiveStartDate = (sixMonthsAgo); product2.EffectiveEndDate = (DateTime.Today); + product2.ProductGuid = Guid.NewGuid(); + Product2Guid = product2.ProductGuid; Category cat3 = new Category("test cat 2", sixMonthsAgo, DateTime.Today); product2.AddCategory(cat3); diff --git a/src/NHibernate.Test/FilterTest/Product.cs b/src/NHibernate.Test/FilterTest/Product.cs index f165dd5e7a8..b8b51020964 100644 --- a/src/NHibernate.Test/FilterTest/Product.cs +++ b/src/NHibernate.Test/FilterTest/Product.cs @@ -75,6 +75,8 @@ public virtual ISet Categories set { categories = value; } } + public virtual Guid ProductGuid { get; set; } + public override int GetHashCode() { return stockNumber; diff --git a/src/NHibernate.Test/FilterTest/classes.hbm.xml b/src/NHibernate.Test/FilterTest/classes.hbm.xml index 3a72339e44c..22286b7745c 100644 --- a/src/NHibernate.Test/FilterTest/classes.hbm.xml +++ b/src/NHibernate.Test/FilterTest/classes.hbm.xml @@ -79,6 +79,8 @@ + + @@ -93,6 +95,7 @@ + @@ -118,4 +121,4 @@ - \ No newline at end of file + diff --git a/src/NHibernate.Test/FilterTest/defs.hbm.xml b/src/NHibernate.Test/FilterTest/defs.hbm.xml index 48acb2807a1..f3a51fcd4ce 100644 --- a/src/NHibernate.Test/FilterTest/defs.hbm.xml +++ b/src/NHibernate.Test/FilterTest/defs.hbm.xml @@ -24,4 +24,8 @@ - \ No newline at end of file + + + + + diff --git a/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs b/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs index 0a1ccb349da..f2e9a275f45 100644 --- a/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs +++ b/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs @@ -151,19 +151,16 @@ private SqlString ExpandDynamicFilterParameters(SqlString sqlString, ICollection string parameterName = parts[1]; var filter = (FilterImpl)enabledFilters[filterName]; - object value = filter.GetParameter(parameterName); + var collectionSpan = filter.GetParameterSpan(parameterName); IType type = filter.FilterDefinition.GetParameterType(parameterName); int parameterColumnSpan = type.GetColumnSpan(session.Factory); - var collectionValue = value as ICollection; - int? collectionSpan = null; // Add query chunk - string typeBindFragment = string.Join(", ", Enumerable.Repeat("?", parameterColumnSpan).ToArray()); + string typeBindFragment = string.Join(", ", Enumerable.Repeat("?", parameterColumnSpan)); string bindFragment; - if (collectionValue != null && !type.ReturnedClass.IsArray) + if (collectionSpan.HasValue && !type.ReturnedClass.IsArray) { - collectionSpan = collectionValue.Count; - bindFragment = string.Join(", ", Enumerable.Repeat(typeBindFragment, collectionValue.Count).ToArray()); + bindFragment = string.Join(", ", Enumerable.Repeat(typeBindFragment, collectionSpan.Value)); } else { diff --git a/src/NHibernate/Impl/FilterImpl.cs b/src/NHibernate/Impl/FilterImpl.cs index f54260d79cb..5153b82baf7 100644 --- a/src/NHibernate/Impl/FilterImpl.cs +++ b/src/NHibernate/Impl/FilterImpl.cs @@ -16,6 +16,7 @@ public class FilterImpl : IFilter private FilterDefinition definition; private readonly IDictionary parameters = new Dictionary(); + private readonly Dictionary _parameterSpans = new Dictionary(); public void AfterDeserialize(FilterDefinition factoryDefinition) { @@ -75,20 +76,21 @@ public IFilter SetParameter(string name, object value) /// The parameter's name. /// The values to be expanded into an SQL IN list. /// This FilterImpl instance (for method chaining). + /// Thrown when or are . public IFilter SetParameterList(string name, ICollection values) { + if (values == null) + throw new ArgumentNullException(nameof(values), "Collection must be not null!"); + var type = definition.GetParameterType(name); if (type == null) - { throw new HibernateException("Undefined filter parameter [" + name + "]"); - } if (!type.ReturnedClass.IsAssignableFrom(typeof(T))) - { throw new HibernateException("Incorrect type for parameter [" + name + "]"); - } - parameters[name] = values ?? throw new ArgumentException("Collection must be not null!", nameof(values)); + _parameterSpans[name] = values.Count; + parameters[name] = values; return this; } @@ -99,6 +101,18 @@ public object GetParameter(string name) return result; } + /// + /// Get the span of a value list parameter by name. if the parameter is not a value list + /// or if there is no such parameter. + /// + /// The parameter name. + /// The parameter span, or if the parameter is not a value list or + /// if there is no such parameter. + public int? GetParameterSpan(string name) + { + return _parameterSpans.TryGetValue(name, out var result) ? result : default(int?); + } + /// /// Perform validation of the filter state. This is used to verify the /// state of the filter after its enablement and before its use. diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index bfe3cc92346..84221432140 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -1859,19 +1859,16 @@ protected SqlString ExpandDynamicFilterParameters(SqlString sqlString, ICollecti string parameterName = parts[1]; var filter = (FilterImpl)enabledFilters[filterName]; - object value = filter.GetParameter(parameterName); + int? collectionSpan = filter.GetParameterSpan(parameterName); IType type = filter.FilterDefinition.GetParameterType(parameterName); int parameterColumnSpan = type.GetColumnSpan(session.Factory); - var collectionValue = value as ICollection; - int? collectionSpan = null; // Add query chunk - string typeBindFragment = string.Join(", ", Enumerable.Repeat("?", parameterColumnSpan).ToArray()); + string typeBindFragment = string.Join(", ", Enumerable.Repeat("?", parameterColumnSpan)); string bindFragment; - if (collectionValue != null && !type.ReturnedClass.IsArray) + if (collectionSpan.HasValue && !type.ReturnedClass.IsArray) { - collectionSpan = collectionValue.Count; - bindFragment = string.Join(", ", Enumerable.Repeat(typeBindFragment, collectionValue.Count).ToArray()); + bindFragment = string.Join(", ", Enumerable.Repeat(typeBindFragment, collectionSpan.Value)); } else {